Encoding video streams in real time

How to enable this feature

Please see this page (in particular the hardware-accelerated HEVC section) for the pre-requisites and pip install options needed to enable this feature.

Example with explanation

This section shows how GIFT-Grab can be used for encoding video frames and saving them to a file. To this end, we first obtain the GIFT-Grab video target factory singleton:

from pygiftgrab import VideoTargetFactory
tfac = VideoTargetFactory.get_instance()

Then we create a file writer using the factory:

from pygiftgrab import Codec
frame_rate = 30.0
file_writer = tfac.create_file_writer(
    Codec.HEVC, '/tmp/myoutput.mp4', frame_rate )

The first argument in the call to create_file_writer() specifies the codec to use for encoding. The third argument is the frame rate of the resulting /tmp/myoutput.mp4 file. The frame_rate could be assigned based on the frame rate of the video source that feeds frames to our file_writer. For instance, if we were using the file_reader created in the Reading video files section, we could query its frame rate:

frame_rate = file_reader.get_frame_rate()

Once we attach this file_writer to a video source, e.g. our frame_reader, it starts receiving video frames, each of which it subsequently encodes using HEVC and writes to /tmp/myoutput.mp4:

file_reader.attach( file_writer )

This pipeline keeps operating until we detach our file_writer from our file_reader:

file_reader.detach( file_writer )

The Processing video frames with SciPy / NumPy section shows a more complex pipeline that implements a custom image processing capability.

Full source code

Below is the full source code of the example explained above.

#!/usr/bin/env python2

from pygiftgrab import VideoTargetFactory
from pygiftgrab import Codec
from time import sleep
from pygiftgrab import VideoSourceFactory
from pygiftgrab import ColourSpace


if __name__ == '__main__':
    sfac = VideoSourceFactory.get_instance()
    file_reader = sfac.create_file_reader(
        '/tmp/myinput.mp4', ColourSpace.I420 )

    tfac = VideoTargetFactory.get_instance()
    frame_rate = file_reader.get_frame_rate()
    file_writer = tfac.create_file_writer(
        Codec.HEVC, '/tmp/myoutput.mp4', frame_rate )

    file_reader.attach( file_writer )

    sleep( 20 )  # operate pipeline for 20 sec

    file_reader.detach( file_writer )