Streaming video processing

This example shows how to process video in streaming fashion.

For the resulting video to be playable, audio data and video data must be written in small chunks in alternating manner.

block-beta columns 7 block:e:7 p1["Audio t1"] p2("Video t1") p3("Video t2") p4["Audio t2"] p5("Video t3") p6["Audio t3"] p7["..."] end

The following diagram illustrates how audio/video data are processed.

flowchart TD In[Input Video] -->|1\. Demux| AP(Audio Packets) AP --> |2\. Remux| Out[Output Video] In[Input Video] -->|1\. Demux| VP(Video Packets) VP --> |3\. Decode| VF("Video Frames (YUV)") VF --> |4\. Filter| VF2("Video Frames (RGB)") VF2 --> |5\. Convert| ARR(Array) ARR --> |6\. Wrap| VF3("Video Frames (RGB)") VF3 --> |7\. Filter| VF4("Video Frames (YUV)") VF4 --> |8\. Encode| VP2(Video Packets) VP2 --> |9\. Mux| Out

We use spdl.io.Demuxer to extract audio/video data from the source. (1)

In this example, we do not modify audio data, so audio packets are sent to muxer (an instance of spdl.io.Muxer) directly. (2)

To modify video data, first we decode videos packets and obtain frames, using spdl.io.VideoDecoder. (3)

Usually, video frames are stored as YUV420 format, so we convert it to RGB using spdl.io.FilterGraph. (4) Then the resulting frame data are extracted as NumPy array. (5)

Though omitted in this example, let’s pretend that the array data is modified with some sort of AI model. Now we convert the array back to packet, by applying a reverse operation one by one.

To convert array back to frames, we use spdl.io.create_reference_video_frame(). This function creates a VideoFrames object that references the data of the array. (6)

We convert RGB into YUV420 using another FilterGraph instance. (7)

The YUV frame is encoded using spdl.io.VideoEncoder. (8)

Finally, the encoded data is written to the multiplexer. (9)

Note on component states

All the media processing components used in this example, (Demuxer/Decoder/FilterGraph/Encoder/Muxer) maintain its own internal state, and do not necessarily process the input data immediately.

Therefore, the number of input/output frames/packets do not necessarily match, and you need to call flush() at the end for each component.

Source

Source

Click here to see the source.
  1#!/usr/bin/env python3
  2# Copyright (c) Meta Platforms, Inc. and affiliates.
  3# All rights reserved.
  4#
  5# This source code is licensed under the BSD-style license found in the
  6# LICENSE file in the root directory of this source tree.
  7
  8"""This example shows how to process video in streaming fashion.
  9
 10For the resulting video to be playable, audio data and video data must be
 11written in small chunks in alternating manner.
 12
 13.. include:: ../plots/streaming_video_processing_block.txt
 14
 15The following diagram illustrates how audio/video data are processed.
 16
 17.. include:: ../plots/streaming_video_processing_chart.txt
 18
 19We use :py:class:`spdl.io.Demuxer` to extract audio/video data from the
 20source. (1)
 21
 22In this example, we do not modify audio data, so audio packets are sent to
 23muxer (an instance of :py:class:`spdl.io.Muxer`) directly. (2)
 24
 25To modify video data, first we decode videos packets and obtain frames,
 26using :py:class:`spdl.io.VideoDecoder`. (3)
 27
 28Usually, video frames are stored as YUV420 format, so we convert
 29it to RGB using :py:class:`spdl.io.FilterGraph`. (4) Then the resulting
 30frame data are extracted as NumPy array. (5)
 31
 32Though omitted in this example, let's pretend that the array data is
 33modified with some sort of AI model. Now we convert the array back
 34to packet, by applying a reverse operation one by one.
 35
 36To convert array back to frames, we use
 37:py:func:`spdl.io.create_reference_video_frame`. This function creates a
 38:py:class:`~spdl.io.VideoFrames` object that references the data of the
 39array. (6)
 40
 41We convert RGB into YUV420 using another :py:class:`~spdl.io.FilterGraph`
 42instance. (7)
 43
 44The YUV frame is encoded using :py:class:`spdl.io.VideoEncoder`. (8)
 45
 46Finally, the encoded data is written to the multiplexer. (9)
 47
 48.. admonition:: Note on component states
 49   :class: note
 50
 51   All the media processing components used in this example,
 52   (Demuxer/Decoder/FilterGraph/Encoder/Muxer) maintain its own internal
 53   state, and do not necessarily process the input data immediately.
 54
 55   Therefore, the number of input/output frames/packets do not necessarily
 56   match, and you need to call ``flush()`` at the end for each component.
 57
 58"""
 59
 60__all__ = [
 61    "main",
 62    "parse_args",
 63    "get_filter_desc",
 64    "process",
 65    "build_components",
 66    "main",
 67]
 68
 69import argparse
 70from pathlib import Path
 71from typing import TYPE_CHECKING
 72
 73import spdl.io
 74from spdl.io import (
 75    Demuxer,
 76    FilterGraph,
 77    Muxer,
 78    VideoDecoder,
 79    VideoEncoder,
 80    VideoPackets,
 81)
 82
 83if TYPE_CHECKING:
 84    from spdl.io import AudioPackets, ImagePackets
 85
 86
 87def parse_args() -> argparse.Namespace:
 88    """Parse the command line arguments."""
 89
 90    parser = argparse.ArgumentParser(
 91        description=__doc__,
 92    )
 93    parser.add_argument("--input-path", "-i", required=True, type=Path)
 94    parser.add_argument("--output-path", "-o", required=True, type=Path)
 95    return parser.parse_args()
 96
 97
 98def get_filter_desc(
 99    input_pix_fmt: str,
100    input_width: int,
101    input_height: int,
102    frame_rate: tuple[int, int],
103    output_pix_fmt: str,
104    output_width: int | None = None,
105    output_height: int | None = None,
106) -> str:
107    """Build a filter description that performs format conversion and optional scaling
108
109    Args:
110        input_pix_fmt: The input pixel format. Usually ``"rgb24"``.
111        input_width,input_height: The input frame resolution.
112        frame_rate: The frame rate of the video.
113        output_pix_fmt: The output pixel format. It is the pixel format used by
114            the encoder.
115        output_width,output_height: The output frame resolution.
116
117    Returns:
118        The filter description.
119    """
120    # filter graph for converting RGB into YUV420p
121    buffer_arg = ":".join(
122        [
123            f"video_size={input_width}x{input_height}",
124            f"pix_fmt={input_pix_fmt}",
125            f"time_base={frame_rate[1]}/{frame_rate[0]}",
126            "pixel_aspect=1/1",
127        ]
128    )
129    filter_arg = ",".join(
130        [
131            f"format=pix_fmts={output_pix_fmt}",
132            f"scale=w={output_width or 'iw'}:h={output_height or 'ih'}",
133        ]
134    )
135    return f"buffer={buffer_arg},{filter_arg},buffersink"
136
137
138def process(
139    demuxer: Demuxer,
140    video_decoder: VideoDecoder,
141    filter_graph: FilterGraph,
142    video_encoder: VideoEncoder,
143    muxer: Muxer,
144) -> None:
145    """The main processing logic.
146
147    Args:
148        demuxer: Demux audio/video streams from the source.
149        video_decoder: Decode the video packets.
150        filter_graph: Transform applied to the array data before encoding.
151        video_encoder: Encode the processed video array.
152        muxer: Multiplexer for remuxing audio packets and processed video packets.
153    """
154    frames: spdl.io.AudioFrames | spdl.io.VideoFrames | spdl.io.ImageFrames | None
155    packets: (
156        "dict[int, AudioPackets | VideoPackets | ImagePackets] | VideoPackets | None"
157    )
158    src_pix_fmt = "rgb24"
159    frame_rate = demuxer.video_codec.frame_rate
160    video_index = demuxer.video_stream_index
161    audio_index = demuxer.audio_stream_index
162
163    streaming_demuxing = demuxer.streaming_demux([video_index, audio_index], duration=1)
164    with muxer.open():
165        num_video_frames = 0
166        for packets in streaming_demuxing:
167            if (audio_packets := packets.get(audio_index)) is not None:
168                muxer.write(1, audio_packets)  # type: ignore[arg-type]
169
170            if (video_packets := packets.get(video_index)) is None:
171                continue
172
173            assert isinstance(video_packets, VideoPackets)
174            for frames in video_decoder.streaming_decode_packets(video_packets):
175                buffer = spdl.io.convert_frames(frames)
176                array = spdl.io.to_numpy(buffer)
177
178                ##############################################################
179                # <ADD FRAME PROCESSING HERE>
180                ##############################################################
181
182                frames = spdl.io.create_reference_video_frame(
183                    array,
184                    pix_fmt=src_pix_fmt,
185                    frame_rate=frame_rate,
186                    pts=num_video_frames,
187                )
188                num_video_frames += len(array)
189
190                filter_graph.add_frames(frames)
191
192                if (frames := filter_graph.get_frames()) is not None:
193                    if (
194                        packets := video_encoder.encode(
195                            frames  # type: ignore[arg-type]
196                        )
197                    ) is not None:
198                        muxer.write(0, packets)
199
200        # -------------------------------------------------------------
201        # Drain mode
202        # -------------------------------------------------------------
203
204        # Flush decoder
205        for frames in video_decoder.flush():
206            buffer = spdl.io.convert_frames(frames)
207            array = spdl.io.to_numpy(buffer)
208
209            ##############################################################
210            # <ADD FRAME PROCESSING HERE>
211            ##############################################################
212
213            frames = spdl.io.create_reference_video_frame(
214                array,
215                pix_fmt=src_pix_fmt,
216                frame_rate=frame_rate,
217                pts=num_video_frames,
218            )
219            num_video_frames += len(frames)
220
221            filter_graph.add_frames(frames)
222            if (frames := filter_graph.get_frames()) is not None:
223                if (
224                    packets := video_encoder.encode(frames)  # type: ignore[arg-type]
225                ) is not None:
226                    muxer.write(0, packets)
227
228        # Flush filter graph
229        if (frames := filter_graph.flush()) is not None:  # type: ignore[func-returns-value]
230            if (packets := video_encoder.encode(frames)) is not None:
231                muxer.write(0, packets)
232
233        # Flush encoder
234        if (packets := video_encoder.flush()) is not None:
235            muxer.write(0, packets)
236
237
238def build_components(
239    input_path: Path, output_path: Path
240) -> tuple[Demuxer, VideoDecoder, FilterGraph, VideoEncoder, Muxer]:
241    """"""
242    demuxer = spdl.io.Demuxer(input_path)
243    muxer = spdl.io.Muxer(output_path)
244
245    # Fetch the input config
246    audio_codec = demuxer.audio_codec
247
248    video_codec = demuxer.video_codec
249    frame_rate = video_codec.frame_rate
250    src_width = video_codec.width
251    src_height = video_codec.height
252
253    # Create decoder
254    video_decoder = spdl.io.Decoder(demuxer.video_codec)
255
256    # Configure output
257    src_pix_fmt = "rgb24"
258    enc_pix_fmt = "yuv420p"
259    enc_height = src_height // 2
260    enc_width = src_width // 2
261    filter_desc = get_filter_desc(
262        input_pix_fmt=src_pix_fmt,
263        input_width=src_width,
264        input_height=src_height,
265        frame_rate=frame_rate,
266        output_pix_fmt=enc_pix_fmt,
267        output_width=enc_width,
268        output_height=enc_height,
269    )
270    print(filter_desc)
271    filter_graph = spdl.io.FilterGraph(filter_desc)
272
273    video_encoder = muxer.add_encode_stream(
274        config=spdl.io.video_encode_config(
275            pix_fmt=enc_pix_fmt,
276            frame_rate=frame_rate,
277            height=enc_height,
278            width=enc_width,
279            colorspace="bt709",
280            color_primaries="bt709",
281            color_trc="bt709",
282        ),
283    )
284    muxer.add_remux_stream(audio_codec)
285    return demuxer, video_decoder, filter_graph, video_encoder, muxer
286
287
288def main() -> None:
289    """Entrypoint from the command line."""
290    args = parse_args()
291
292    demuxer, video_decoder, filter_graph, video_encoder, muxer = build_components(
293        args.input_path, args.output_path
294    )
295
296    process(
297        demuxer,
298        video_decoder,
299        filter_graph,
300        video_encoder,
301        muxer,
302    )
303
304
305if __name__ == "__main__":
306    main()

API Reference

Functions

main() → None[source]

Entrypoint from the command line.

parse_args() → Namespace[source]

Parse the command line arguments.

get_filter_desc(input_pix_fmt: str, input_width: int, input_height: int, frame_rate: tuple[int, int], output_pix_fmt: str, output_width: int | None = None, output_height: int | None = None) → str[source]

Build a filter description that performs format conversion and optional scaling

Parameters:
  • input_pix_fmt – The input pixel format. Usually "rgb24".

  • input_width – The input frame resolution.

  • input_height – The input frame resolution.

  • frame_rate – The frame rate of the video.

  • output_pix_fmt – The output pixel format. It is the pixel format used by the encoder.

  • output_width – The output frame resolution.

  • output_height – The output frame resolution.

Returns:

The filter description.

process(demuxer: Demuxer, video_decoder: VideoDecoder, filter_graph: FilterGraph, video_encoder: VideoEncoder, muxer: Muxer) → None[source]

The main processing logic.

Parameters:
  • demuxer – Demux audio/video streams from the source.

  • video_decoder – Decode the video packets.

  • filter_graph – Transform applied to the array data before encoding.

  • video_encoder – Encode the processed video array.

  • muxer – Multiplexer for remuxing audio packets and processed video packets.

build_components(input_path: Path, output_path: Path) → tuple[Demuxer, VideoDecoder, FilterGraph, VideoEncoder, Muxer][source]