Gstreamer конвейер для кодирования анимации - PullRequest
0 голосов
/ 03 ноября 2019

Я новичок в Gstreamer, и у меня возникла проблема с записью файла h.265 с использованием конвейера Gstreamer, где изображения генерируются из приложения - анимация. Мой текущий конвейер выглядит следующим образом:

'gst-launch-1.0 appsrc ! autovideoconvert ! omxh265enc ! matroskamux ! filesink location = testGStreamer.mkv '

Чтобы проиллюстрировать проблему, я собрал очень простую анимацию в Python, где круги движутся в разных направлениях - зеленые, синие и красные круги движутся горизонтально, вертикально игусеничный соответственно. Использование FFMEPG приводит к правильному выводу h.265, но он использует CPU для кодирования. Использование Gstreamer должно использовать преимущества аппаратного кодировщика Jetson Nano, если я смогу заставить поток работать полностью. С моим текущим конвейером я могу написать файл h.265, но нет кругов или анимации, а фон имеет зеленый оттенок, когда должен быть черным.

Это неполный список вещей, которыеЯ пытался:

  • Использование h.264 вместо h.265 дает тот же результат: 'gst-launch-1.0 appsrc! автовидеконверт! x264enc! mp4mux! filesink location = testGStreamer.mp4 '
  • При удалении кодировщика создается пустой файл:' gst-launch-1.0 appsrc! автовидеконверт! mp4mux! filesink location = testGStreamer.mp4 '
  • изменение цвета приводит к созданию пустого файла:' gst-launch-1.0 appsrc! видео / x-raw, формат = BGR, ширина = 411, высота = 411! видеоконвертер! видео / x-raw, формат = RGB! x264enc! mp4mux! filesink location = testGStreamer.mp4 '

Меня меньше волнует, является ли контейнер mp4 или mkv. В большинстве моих попыток использовался omxh265enc, поскольку он рекомендован на веб-сайте nvidia.

Любая помощь или конструктивная критика приветствуются!

Моя информация о сборке следующая:

General configuration for OpenCV 4.1.0 =====================================
  Version control:               unknown

  Extra modules:
    Location (extra):            /home/paul/opencv_contrib-4.1.0/modules
    Version control (extra):     unknown

  Platform:
    Timestamp:                   2019-10-11T19:31:30Z
    Host:                        Linux 4.9.140-tegra aarch64
    CMake:                       3.10.2
    CMake generator:             Unix Makefiles
    CMake build tool:            /usr/bin/make
    Configuration:               RELEASE

  CPU/HW features:
    Baseline:                    NEON FP16
      required:                  NEON
      disabled:                  VFPV3

  C/C++:
    Built as dynamic libs?:      YES
    C++ Compiler:                /usr/bin/c++  (ver 7.4.0)
    C++ flags (Release):         -fsigned-char -W -Wall -Werror=return-type -Werror=non-virtual-dtor -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wundef -Winit-self -Wpointer-arith -Wshadow -Wsign-promo -Wuninitialized -Winit-self -Wno-delete-non-virtual-dtor -Wno-comment -Wimplicit-fallthrough=3 -Wno-strict-overflow -fdiagnostics-show-option -pthread -fomit-frame-pointer -ffunction-sections -fdata-sections    -fvisibility=hidden -fvisibility-inlines-hidden -O3 -DNDEBUG  -DNDEBUG
    C++ flags (Debug):           -fsigned-char -W -Wall -Werror=return-type -Werror=non-virtual-dtor -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wundef -Winit-self -Wpointer-arith -Wshadow -Wsign-promo -Wuninitialized -Winit-self -Wno-delete-non-virtual-dtor -Wno-comment -Wimplicit-fallthrough=3 -Wno-strict-overflow -fdiagnostics-show-option -pthread -fomit-frame-pointer -ffunction-sections -fdata-sections    -fvisibility=hidden -fvisibility-inlines-hidden -g  -O0 -DDEBUG -D_DEBUG
    C Compiler:                  /usr/bin/cc
    C flags (Release):           -fsigned-char -W -Wall -Werror=return-type -Werror=non-virtual-dtor -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wmissing-prototypes -Wstrict-prototypes -Wundef -Winit-self -Wpointer-arith -Wshadow -Wuninitialized -Winit-self -Wno-comment -Wimplicit-fallthrough=3 -Wno-strict-overflow -fdiagnostics-show-option -pthread -fomit-frame-pointer -ffunction-sections -fdata-sections    -fvisibility=hidden -O3 -DNDEBUG  -DNDEBUG
    C flags (Debug):             -fsigned-char -W -Wall -Werror=return-type -Werror=non-virtual-dtor -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wmissing-prototypes -Wstrict-prototypes -Wundef -Winit-self -Wpointer-arith -Wshadow -Wuninitialized -Winit-self -Wno-comment -Wimplicit-fallthrough=3 -Wno-strict-overflow -fdiagnostics-show-option -pthread -fomit-frame-pointer -ffunction-sections -fdata-sections    -fvisibility=hidden -g  -O0 -DDEBUG -D_DEBUG
    Linker flags (Release):      -Wl,--gc-sections  
    Linker flags (Debug):        -Wl,--gc-sections  
    ccache:                      NO
    Precompiled headers:         YES
    Extra dependencies:          m pthread cudart_static -lpthread dl rt nppc nppial nppicc nppicom nppidei nppif nppig nppim nppist nppisu nppitc npps cublas cufft -L/usr/local/cuda/lib64 -L/usr/lib/aarch64-linux-gnu
    3rdparty dependencies:

  OpenCV modules:
    To be built:                 aruco bgsegm bioinspired calib3d ccalib core cudaarithm cudabgsegm cudacodec cudafeatures2d cudafilters cudaimgproc cudalegacy cudaobjdetect cudaoptflow cudastereo cudawarping cudev datasets dnn dnn_objdetect dpm face features2d flann freetype fuzzy gapi hdf hfs highgui img_hash imgcodecs imgproc line_descriptor ml objdetect optflow phase_unwrapping photo plot python2 python3 quality reg rgbd saliency shape stereo stitching structured_light superres surface_matching text tracking video videoio videostab xfeatures2d ximgproc xobjdetect xphoto
    Disabled:                    world
    Disabled by dependency:      -
    Unavailable:                 cnn_3dobj cvv java js matlab ovis sfm ts viz
    Applications:                apps
    Documentation:               NO
    Non-free algorithms:         NO

  GUI: 
    GTK+:                        YES (ver 2.24.32)
      GThread :                  YES (ver 2.56.4)
      GtkGlExt:                  NO
    VTK support:                 NO

  Media I/O: 
    ZLib:                        /usr/lib/aarch64-linux-gnu/libz.so (ver 1.2.11)
    JPEG:                        /usr/lib/aarch64-linux-gnu/libjpeg.so (ver 80)
    WEBP:                        build (ver encoder: 0x020e)
    PNG:                         /usr/lib/aarch64-linux-gnu/libpng.so (ver 1.6.34)
    TIFF:                        build (ver 42 - 4.0.10)
    JPEG 2000:                   build (ver 1.900.1)
    OpenEXR:                     build (ver 1.7.1)
    HDR:                         YES
    SUNRASTER:                   YES
    PXM:                         YES
    PFM:                         YES

  Video I/O:
    DC1394:                      YES (2.2.5)
    FFMPEG:                      YES
      avcodec:                   YES (57.107.100)
      avformat:                  YES (57.83.100)
      avutil:                    YES (55.78.100)
      swscale:                   YES (4.8.100)
      avresample:                NO
    GStreamer:                   YES (1.14.5)
    v4l/v4l2:                    YES (linux/videodev2.h)

  Parallel framework:            pthreads

  Trace:                         YES (built-in)

  Other third-party libraries:
    Lapack:                      NO
    Eigen:                       YES (ver 3.3.4)
    Custom HAL:                  YES (carotene (ver 0.0.1))
    Protobuf:                    build (3.5.1)

  NVIDIA CUDA:                   YES (ver 10.0, CUFFT CUBLAS)
    NVIDIA GPU arch:             53
    NVIDIA PTX archs:

  OpenCL:                        YES (no extra features)
    Include path:                /home/paul/opencv-4.1.0/3rdparty/include/opencl/1.2
    Link libraries:              Dynamic load

  Python 2:
    Interpreter:                 /usr/bin/python2.7 (ver 2.7.15)
    Libraries:                   /usr/lib/aarch64-linux-gnu/libpython2.7.so (ver 2.7.15+)
    numpy:                       /usr/lib/python2.7/dist-packages/numpy/core/include (ver 1.13.3)
    install path:                lib/python2.7/dist-packages/cv2/python-2.7

  Python 3:
    Interpreter:                 /usr/bin/python3 (ver 3.6.8)
    Libraries:                   /usr/lib/aarch64-linux-gnu/libpython3.6m.so (ver 3.6.8)
    numpy:                       /usr/local/lib/python3.6/dist-packages/numpy/core/include (ver 1.17.2)
    install path:                lib/python3.6/dist-packages/cv2/python-3.6

  Python (for build):            /usr/bin/python2.7

  Java:                          
    ant:                         NO
    JNI:                         NO
    Java wrappers:               NO
    Java tests:                  NO

  Install to:                    /usr/local
-----------------------------------------------------------------

Простой код анимации:

import cv2
import numpy as np

def getVideoWriterFFMPEG(fps, width, height):
    """ create FFMPEG writer that will create a h.265 video
        clip from raw image frames """

    fourcc = cv2.VideoWriter_fourcc(*'mp4v')
    return cv2.VideoWriter('testFFMPEG.mp4', fourcc, fps, (width, height))

def getVideoWriterGStreamer(fps, width, height):
    """ create gstreamer pipeline that will create a h.265 video
        clip from raw image frames """

    gstStr = 'gst-launch-1.0 appsrc ! autovideoconvert ! omxh265enc ! h265parse ! matroskamux ! filesink location = testGStreamer.mkv '

    fourcc = cv2.VideoWriter_fourcc(*'mp4v')
    return cv2.VideoWriter(gstStr, fourcc, fps, (width, height))

if __name__ == '__main__':
    # video parameters
    fps = 30
    width, height = 411, 411

    # circle constants
    radius, thickness = 40, -1  # fill in the circle
    red = (0, 0, 255)           # color in BGR
    green = (0, 255, 0)         # color in BGR
    blue = (255, 0, 0)          # color in BGR

    writers = [('ffmpeg', getVideoWriterFFMPEG(fps, width, height)),
               ('gstreamer', getVideoWriterGStreamer(fps, width, height))]

    for name, writer in writers:
        print(f'\n==== Start Animation ({name}) ====')
        for i in range(radius, height - radius):
            img = np.zeros((height, width, 3), np.uint8)
            cv2.circle(img, (i, i), radius, red, thickness)
            cv2.circle(img, (i, radius), radius, green, thickness)
            cv2.circle(img, (radius, i), radius, blue, thickness)
            writer.write(img)
        writer.release()
        print(f'==== Animation Complete ({name}) ====')

...