spdl.io.CudaDecoders¶
- class CudaDecoders[source]¶
Interface to the NVDEC hardware video decoders of one CUDA device.
Decoding is its main feature: clips are decoded concurrently, as fast as the device allows, whether they come from many threads calling
decode()or from one thread keeping many clips in flight withdecode_future()ordecode_async(). Create one withcuda_decoders(), and use one object per GPU, shared by threads and event loops.decode() / decode_future() / decode_async() from any number of threads or event loops | vCudaDecoders (one per CUDA device)
- Clip queue [clip] [clip] [clip] …
v
- Thread pool [lane 1] [lane 2] … [lane L]
- ^
- lease | | return
v |
- Decoder pool [decoder] [decoder] [decoder] …
- pictures | | evict
- vDestroyer thread
- - - - - - - - - - - - - - - - - - - - - -
v
NVDEC engines [engine 1] [engine 2] … [engine E]
frames, copied by the lanesv
CUDABuffer (on the GPU, one buffer per clip)
Clip queue: the decoding methods only append a clip to this FIFO queue, after allocating its output buffer on the calling thread.
decode()then waits for the clip with the GIL released.Thread pool: a fixed pool of
Lworker threads, called lanes (num_lanes, by default2 x E). Each lane takes the next clip from the queue and decodes it: it parses the bitstream (with one parser per codec, kept across clips), leases a decoder, submits the pictures and copies the frames into the output. SoLclips are decoded concurrently, however many threads call the decoding methods. The lanes never take the GIL.Decoder pool: the NVDEC decoders, shared by all lanes. A decoder can decode any stream of its codec, chroma format and bit depth up to the size it was created for, and reconfiguring it for another size takes microseconds, while creating one takes tens of milliseconds. For each clip, a lane leases the smallest idle decoder that fits the stream and reconfigures it, or, if none fits, creates one at the smallest of the
size_bucketscovering the stream. It returns the decoder to the pool when the clip is done, ready for any lane. The pool grows only when no idle decoder fits, so clips of similar codecs and sizes share a few decoders.Destroyer thread: destroying a decoder takes hundreds of milliseconds. When the estimated memory of the idle decoders exceeds
max_memory_bytes, the least recently used ones are evicted and destroyed on this thread, so no lane waits for it. Withoutmax_memory_bytes(the default), the pool keeps its decoders untilshutdown().NVDEC engines: the
Ehardware decode engines of the GPU, shared with other processes. Lanes are not bound to engines: the driver spreads the pictures of all decoders over all engines. A lane also spends time on the host for each clip (parsing, waiting for decoded frames, setup), hence two lanes per engine by default.
The device side is initialized when the object is entered as a context manager, or at the first decoding call otherwise.
Threads used
num_lanesworker threads (by default, twice the number of NVDEC engines of the device) and one thread that destroys evicted decoders. A busy worker uses about 0.1 CPU core, mostly for bitstream parsing. The worker threads never take the GIL.Compared with
NvDecDecoderWith warm decoders, both decode at the same speed for the same number of decoder threads (lanes here, Python threads there). This class is easier to use: one object manages the threads and decoders for the whole GPU, creates far fewer decoders when clips vary, and destroys evicted decoders off the decoding path. The outputs of queued clips are allocated at submission, so bound the clips in flight to bound memory. See CudaDecoders or NvDecDecoder?.
See also
Benchmark video training: end-to-end training throughput with these decoders, and where to place them.
Added in version 0.10.0.
Methods
decode(packets, *[, pix_fmt, frame_indices, ...])Decode one clip and wait for it.
decode_async(packets, *[, pix_fmt, ...])Like
decode(), but return an asyncio future.decode_future(packets, *[, pix_fmt, ...])Like
decode(), but return a future without waiting.shutdown([wait])Finish the queued clips, then release the decoders and threads.
stats()Return a snapshot of the counters for performance analysis.
supports(codec)Return whether the GPU can decode the stream.
- decode(packets: VideoPackets, *, pix_fmt: PixFmt = 'nv12', frame_indices: Sequence[int] | None = None, crop_left: int = 0, crop_top: int = 0, crop_right: int = 0, crop_bottom: int = 0, scale_width: int = -1, scale_height: int = -1) CUDABuffer[source]¶
Decode one clip and wait for it.
The calling thread waits with the GIL released, and no Python future is created. The output is allocated by the calling thread with the allocator of the CUDA config. Call it from as many threads as needed: the clips are queued and decoded by the worker threads.
- Parameters:
packets – Video packets of one clip. The packets are consumed. H.264 and HEVC packets must be in Annex B format, which
demux_video()produces withbsf="h264_mp4toannexb"orbsf="hevc_mp4toannexb". Frames outside of the time window of the packets are dropped.pix_fmt –
Pixel format of the output.
"nv12":uint8[num_frames, height * 3 // 2, width]. 10/12-bit 4:2:0 streams are converted to 8 bits."rgb","bgr": planaruint8[num_frames, 3, height, width](BT.709), converted directly from the decoder output.
The format is chosen per clip; the decoders are shared by all formats.
frame_indices – The frames of the time window to output, as indices from its first frame (in presentation order), non-negative and strictly increasing.
Noneoutputs all frames. The other frames are still decoded, because later frames can refer to them, but they are not mapped, converted or copied. When a clip samples a few of its frames (e.g. 16 of 64 for training), this saves GPU work and CUDA calls, and the output holds onlylen(frame_indices)frames.crop_left – Pixels removed from each side of the frame by the decoder, before scaling.
crop_top – Pixels removed from each side of the frame by the decoder, before scaling.
crop_right – Pixels removed from each side of the frame by the decoder, before scaling.
crop_bottom – Pixels removed from each side of the frame by the decoder, before scaling.
scale_width –
Size of the output frames, after cropping, resized by the decoder. Must be even.
-1keeps the cropped size. The output shapes ofpix_fmtuse this size.Crop and scale are chosen per clip, like
pix_fmt, and match those ofdecode_packets_nvdec().scale_height –
Size of the output frames, after cropping, resized by the decoder. Must be even.
-1keeps the cropped size. The output shapes ofpix_fmtuse this size.Crop and scale are chosen per clip, like
pix_fmt, and match those ofdecode_packets_nvdec().
- Returns:
The decoded frames.
- Raises:
NvDecUnsupportedStreamError – The GPU does not support the stream.
ValueError – The packets are not in Annex B format,
frame_indicesis empty, negative or not strictly increasing, the crop is negative or leaves no pixels, or the scale is not positive and even.RuntimeError – Decoding failed, e.g. an index in
frame_indicesis beyond the frames of the time window.
The frames are ordered on the stream of the CUDA config on the device: no host synchronization is needed. If that stream is the per-thread default stream (the default of
cuda_config()), it is the one of the thread that receives the result.
- decode_async(packets: VideoPackets, *, pix_fmt: PixFmt = 'nv12', frame_indices: Sequence[int] | None = None, crop_left: int = 0, crop_top: int = 0, crop_right: int = 0, crop_bottom: int = 0, scale_width: int = -1, scale_height: int = -1) asyncio.Future[CUDABuffer][source]¶
Like
decode(), but return an asyncio future.Must be called from a running event loop. The future is completed on that loop; the decoding threads only signal the loop (through a file descriptor, or a socket pair on Windows), and no thread waits per clip.
Example
async def decode(packets): return await decoders.decode_async(packets, pix_fmt="rgb")
- Parameters:
- Returns:
An awaitable future of the decoded frames.
- decode_future(packets: VideoPackets, *, pix_fmt: PixFmt = 'nv12', frame_indices: Sequence[int] | None = None, crop_left: int = 0, crop_top: int = 0, crop_right: int = 0, crop_bottom: int = 0, scale_width: int = -1, scale_height: int = -1) _NativeFuture[CUDABuffer][source]¶
Like
decode(), but return a future without waiting.The queue is unbounded, so bound the clips in flight on the caller side (e.g. with the concurrency of a pipeline stage).
- Parameters:
- Returns:
The future of the clip. It implements
result(),exception()anddone()ofconcurrent.futures.Future(resultandexceptiontake atimeoutand wait with the GIL released). The lanes complete it without taking the GIL. A clip that cannot be decoded fails only its own future. The result is ordered like that ofdecode().
- shutdown(wait: bool = True) None[source]¶
Finish the queued clips, then release the decoders and threads.
- Parameters:
wait – Wait for the teardown. Destroying a decoder takes about 0.2 seconds. If
False, the teardown runs in the background.
Later submissions raise
RuntimeError.
- stats() DecodersStats[source]¶
Return a snapshot of the counters for performance analysis.
See
DecodersStatsfor what they mean and how to read them.
- supports(codec: VideoCodec) bool[source]¶
Return whether the GPU can decode the stream.
- Parameters:
codec – The codec of the stream, e.g.
packets.codec.