Rate this Page
★ ★ ★ ★ ★

AudioPacketDecoder#

class torchcodec.decoders.AudioPacketDecoder(codec_parameters: AudioCodecParameters)[source]#

Decodes the compressed Packets of one audio stream into RawAudioSamples.

This is a low-level API: for straightforward decoding, use AudioDecoder instead.

Build it from the AudioCodecParameters of the stream to decode, then feed it one packet at a time, and drain it at the end:

demuxer = Demuxer("audio.mp3", streams="audio")
decoder = AudioPacketDecoder(demuxer.streams[0].codec_parameters)

for packet in demuxer:
    for raw_samples in decoder.decode(packet):
        ...
for raw_samples in decoder.drain():
    ...

The codec parameters can also be pickled, to decode in another process than the demuxer, or built by hand, to decode packets that don’t come from a Demuxer (see Decoding packets that don’t come from a Demuxer). Audio is always decoded on the CPU.

It is stateful. A lossy codec carries state from one frame to the next, so it expects the packets of its own stream, in the order the demuxer produced them. After a Demuxer.seek(), reset() is necessary but not sufficient: the first samples that come out are subtly wrong until the codec re-primes, so decode a margin before your target and throw it away.

Parameters:

codec_parameters (AudioCodecParameters) – The parameters of the stream to decode, e.g. AudioStream.codec_parameters.

Examples using AudioPacketDecoder:

Build your own decoding pipeline

Build your own decoding pipeline

Raw frames and raw audio samples

Raw frames and raw audio samples
decode(packet: Packet) → list[RawAudioSamples][source]#

Send one Packet to the codec and return the RawAudioSamples that are ready.

This can return zero, one, or more than one RawAudioSamples. What comes back is not the decoding of the packet you just passed: a codec that is still priming itself will emit what it owes you on a later call.

Parameters:

packet (Packet) – A packet of this decoder’s own stream.

Returns:

The possibly empty list of RawAudioSamples that the codec has ready, in presentation order.

Raises:

RuntimeError – If this decoder has been drained, or if the demuxer seeked without it being reset() afterwards.

drain() → list[RawAudioSamples][source]#

Tell the codec the stream has ended, and return the RawAudioSamples it was still holding.

Skipping this loses the tail of the stream. A drained decoder refuses any further packet; reset() makes it usable again.

Returns:

The possibly empty list of RawAudioSamples that the codec was still holding, in presentation order.

reset() → None#

Drop the codec’s buffered state and start over.

Needed after a Demuxer.seek(), and after drain().