This is an automated email from the ASF dual-hosted git repository.

JingsongLi pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/paimon.git


The following commit(s) were added to refs/heads/master by this push:
     new c0b306929a [python] Reuse indexed PyAV video sessions across batches 
(#10979)
c0b306929a is described below

commit c0b306929a8682559a6bce967841b5de07c9fa12
Author: Yann Byron <[email protected]>
AuthorDate: Wed Nov 4 14:24:53 2026 +0800

    [python] Reuse indexed PyAV video sessions across batches (#10979)
---
 .../pypaimon/multimodal/lerobot/dataset.py         | 57 +++++++++-----
 .../pypaimon/tests/multimodal_lerobot_test.py      | 86 ++++++++++++++++++++++
 .../tests/video_decode_parallelism_test.py         |  4 +-
 3 files changed, 126 insertions(+), 21 deletions(-)

diff --git a/paimon-python/pypaimon/multimodal/lerobot/dataset.py 
b/paimon-python/pypaimon/multimodal/lerobot/dataset.py
index 7dacc8fbb1..847dd1cf69 100644
--- a/paimon-python/pypaimon/multimodal/lerobot/dataset.py
+++ b/paimon-python/pypaimon/multimodal/lerobot/dataset.py
@@ -1927,8 +1927,11 @@ class _RangeBackedVideo(io.RawIOBase):
                 remaining -= size
         self._ensure(selected)
 
-    def close(self):
+    def clear_cache(self):
         self._segments.clear()
+
+    def close(self):
+        self.clear_cache()
         super().close()
 
     def _ensure(self, ranges):
@@ -2012,6 +2015,7 @@ class _PyAVVideoDecoder:
             keyframe_index.ordinals
             if keyframe_index is not None else [])
         self._container = None
+        self._indexed_source = None
         self._stream = None
         self._next_index = 0
         self._timestamps = []
@@ -2111,26 +2115,32 @@ class _PyAVVideoDecoder:
         import av
         groups, unused_ranges = self._indexed_plan(indices)
         decoded = {}
-        source = _RangeBackedVideo(
-            self._video_length(), self._read_video_ranges)
         try:
-            source.prefetch(self._keyframe_index.metadata_ranges)
-            with av.open(source) as container:
-                stream = container.streams.video[0]
-                stream.thread_count = self._thread_count
-                for anchor, targets in sorted(groups.items()):
-                    unused_groups, ranges = self._indexed_plan(targets)
-                    source.prefetch(ranges)
-                    self._decode_indexed_group(
-                        container,
-                        stream,
-                        anchor,
-                        sorted(targets),
-                        decoded,
-                    )
+            if self._container is None:
+                self._indexed_source = _RangeBackedVideo(
+                    self._video_length(), self._read_video_ranges)
+                
self._indexed_source.prefetch(self._keyframe_index.metadata_ranges)
+                self._container = av.open(self._indexed_source)
+                self._stream = self._container.streams.video[0]
+                self._stream.thread_count = self._thread_count
+            for anchor, targets in sorted(groups.items()):
+                unused_groups, ranges = self._indexed_plan(targets)
+                self._indexed_source.prefetch(ranges)
+                self._decode_indexed_group(
+                    self._container,
+                    self._stream,
+                    anchor,
+                    sorted(targets),
+                    decoded,
+                )
             return decoded
+        except BaseException:
+            self.close()
+            raise
         finally:
-            source.close()
+            if self._indexed_source is not None:
+                # Reuse the demuxer without retaining media bytes between 
batches.
+                self._indexed_source.clear_cache()
 
     def _indexed_plan(self, indices):
         mapping = self._keyframe_index
@@ -2271,8 +2281,15 @@ class _PyAVVideoDecoder:
         return torch.from_numpy(array).permute(2, 0, 1)
 
     def close(self):
-        if self._container is not None:
-            self._container.close()
+        container, self._container = self._container, None
+        source, self._indexed_source = self._indexed_source, None
+        try:
+            if container is not None:
+                container.close()
+        finally:
+            if source is not None:
+                self._stream = None
+                source.close()
 
 
 def _merge_video_ranges(ranges):
diff --git a/paimon-python/pypaimon/tests/multimodal_lerobot_test.py 
b/paimon-python/pypaimon/tests/multimodal_lerobot_test.py
index 2a2fd90fde..13e0043e6c 100644
--- a/paimon-python/pypaimon/tests/multimodal_lerobot_test.py
+++ b/paimon-python/pypaimon/tests/multimodal_lerobot_test.py
@@ -664,6 +664,92 @@ class LeRobotValidationTest(unittest.TestCase):
                 finally:
                     decoder.close()
 
+    @unittest.skipUnless(
+        av is not None and importlib.util.find_spec("torch") is not None,
+        "PyAV and Torch are required for video decoding",
+    )
+    def test_indexed_pyav_decoder_reuses_session_across_batches(self):
+        output = io.BytesIO()
+        with av.open(output, mode="w", format="mp4") as container:
+            stream = container.add_stream("libx264", rate=30)
+            stream.width = stream.height = 32
+            stream.pix_fmt = "yuv420p"
+            stream.options = {"x264-params":
+                              
"keyint=12:min-keyint=12:scenecut=0:bframes=2:threads=1"}
+            for ordinal in range(48):
+                frame = av.VideoFrame.from_ndarray(
+                    np.full((32, 32, 3), ordinal * 4, dtype=np.uint8),
+                    format="rgb24")
+                for packet in stream.encode(frame):
+                    container.mux(packet)
+            for packet in stream.encode():
+                container.mux(packet)
+        payload = output.getvalue()
+        index = VideoKeyframeIndex.inspect(io.BytesIO(payload), len(payload))
+        with av.open(io.BytesIO(payload)) as container:
+            expected = [frame.to_ndarray(format="rgb24")
+                        for frame in container.decode(video=0)]
+
+        source = io.BytesIO(payload)
+        decoder = _PyAVVideoDecoder(source, index, thread_count=1)
+        inputs = []
+        original_open = av.open
+
+        def open_container(value):
+            inputs.append(value)
+            return original_open(value)
+
+        try:
+            with patch.object(av, "open", side_effect=open_container):
+                for indices in ([31, 0, 12, 31], [45, 2, 17, 45], [0, 47, 1]):
+                    actual = decoder.get_frames_at(indices=indices).data
+                    np.testing.assert_array_equal(
+                        np.stack([expected[i] for i in indices]),
+                        actual.permute(0, 2, 3, 1).numpy())
+            self.assertEqual(1, len(inputs))
+            self.assertFalse(inputs[0].closed)
+            self.assertEqual([], inputs[0]._segments)
+        finally:
+            decoder.close()
+        self.assertTrue(inputs[0].closed)
+        self.assertEqual([], inputs[0]._segments)
+        self.assertIsNone(decoder._stream)
+        self.assertFalse(source.closed)
+
+    @unittest.skipUnless(av is not None, "PyAV is required")
+    def test_indexed_pyav_decoder_closes_failed_session_before_retry(self):
+        source = io.BytesIO(b"0123456789abcdef")
+        index = VideoKeyframeIndex([(0, 4)], [(0, 0, 4)])
+        decoder = _PyAVVideoDecoder(source, index)
+        inputs = []
+        containers = []
+
+        def open_container(value):
+            inputs.append(value)
+            container = Mock()
+            container.streams.video = [SimpleNamespace(thread_count=0)]
+            containers.append(container)
+            return container
+
+        with patch.object(av, "open", side_effect=open_container), 
patch.object(
+                decoder, "_decode_indexed_group", 
side_effect=ValueError("decode failed")) as decode:
+            with self.assertRaisesRegex(ValueError, "decode failed"):
+                decoder._decode_indexed([0])
+            self.assertTrue(inputs[0].closed)
+            containers[0].close.assert_called_once_with()
+
+            def read_group(container, stream, anchor, targets, decoded):
+                decoded[0] = b"frame"
+
+            decode.side_effect = read_group
+            self.assertEqual({0: b"frame"}, decoder._decode_indexed([0]))
+            self.assertEqual(2, len(inputs))
+            self.assertFalse(inputs[1].closed)
+        decoder.close()
+        decoder.close()
+        self.assertTrue(inputs[1].closed)
+        containers[1].close.assert_called_once_with()
+
     @unittest.skipUnless(av is not None, "PyAV is required")
     def 
test_indexed_plan_prefetches_requested_gops_with_bounded_lookahead(self):
         source = io.BytesIO(b"")
diff --git a/paimon-python/pypaimon/tests/video_decode_parallelism_test.py 
b/paimon-python/pypaimon/tests/video_decode_parallelism_test.py
index 05a9025afd..43f222f694 100644
--- a/paimon-python/pypaimon/tests/video_decode_parallelism_test.py
+++ b/paimon-python/pypaimon/tests/video_decode_parallelism_test.py
@@ -481,7 +481,9 @@ class VideoDecodeParallelismTest(unittest.TestCase):
                         decode_group = decoder._decode_indexed_group
 
                         def checked_group(container, stream, *args):
-                            self.assertEqual(threads, stream.thread_count)
+                            # FFmpeg resolves thread_count when it opens the 
codec.
+                            if not stream.codec_context.is_open:
+                                self.assertEqual(threads, stream.thread_count)
                             return decode_group(container, stream, *args)
 
                         with patch.object(decoder, '_decode_indexed_group', 
checked_group):

Reply via email to