From c075490726a546168bdf4a2409594568360210ce Mon Sep 17 00:00:00 2001 From: DJ Magar <85457381+DJStompZone@users.noreply.github.com> Date: Wed, 5 Feb 2025 11:01:18 -0600 Subject: [PATCH] Implement len() for FFStream Implemented len() for audio and video streams - Falls back to 0 for valid streams missing duration data - Raises expected TypeError if len() is called on a stream not labelled as audio/video - Slight tweak to the duration_seconds docstring to reflect actual behavior --- ffprobe/ffprobe.py | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/ffprobe/ffprobe.py b/ffprobe/ffprobe.py index f1eb3dc..9457650 100644 --- a/ffprobe/ffprobe.py +++ b/ffprobe/ffprobe.py @@ -148,6 +148,18 @@ def __repr__(self): return template.format(**self.__dict__) + def __len__(self): + """ + Returns the truncated integer duration of the stream (in seconds), if available, defaulting to 0. + + Raises a TypeError if called on a stream that is not labelled as video or audio. + """ + if self.is_video() or self.is_audio(): + return int(float(self.__dict__.get('duration', '0.0'))) + + __subclass = f"[{self.__dict__.get('codec_type', None)}]".replace("[]","") + raise TypeError(f"object of type '{self.__class__.__name__}{__subclass}' has no len()") + def is_audio(self): """ Is this stream labelled as an audio stream? @@ -219,8 +231,8 @@ def frames(self): def duration_seconds(self): """ - Returns the runtime duration of the video stream as a floating point number of seconds. - Returns 0.0 if not a video stream. + Returns the runtime duration of the audio/video stream as a floating point number of seconds. + Returns 0.0 if not an audio stream or video stream. """ if self.is_video() or self.is_audio(): try: