Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

The seek functionality of StreamReader on the video stream does not return the correct frame if the start_time_stamp of the video stream is nonzero. #3824

Open
w238liu opened this issue Aug 7, 2024 · 0 comments

Comments

@w238liu
Copy link

w238liu commented Aug 7, 2024

🐛 Describe the bug

It seems like this repo is not getting actively monitored any more, but I still would like to report this issue with the seek functionality of StreamReader here. I will post another discussion in pytorch forum later.

The issue is the seek functionality of StreamSmart does not seek to the correct position when the start_time_stamp of the video stream is non-zero. To reproduce the bug, use the code below and put the two attached videos in the same folder of the test script.

from typing import Dict

import torch
from torchaudio.io import StreamReader


class TorchaudioWrapper:
    cpu_decoders: Dict[str, str] = {
        "av1": "libaom-av1",
        "hevc": "hevc",
        "h264": "h264",
        "prores": "prores",
    }

    def __init__(self, video_path: str, device: str = 'cpu') -> None:
        self.video = StreamReader(video_path)
        self.src_stream_info = self.video.get_src_stream_info(self.video.default_video_stream)
        self.src_format: str = self.src_stream_info.format
        self.codec = self.src_stream_info.codec

        if device == 'cpu':
            config = {
                'buffer_chunk_size': 50,
                'stream_index': None,
                'decoder': self.cpu_decoders[self.codec],
                "decoder_option": {"threads": str(0)},
                'filter_desc': "scale=sws_flags=accurate_rnd+full_chroma_int:dst_format=rgb24,format=rgb24",
            }
        else:
            raise ValueError(f'Invalid device: {device}. Torchaudio backend only supports "cpu".')

        self.video.add_video_stream(1, **config)
        self.stream = self.video.stream()

    @property
    def fps(self) -> float:
        fps = self.src_stream_info.frame_rate
        return fps

    def __len__(self) -> int:
        num_frames = self.src_stream_info.num_frames
        return num_frames

    def seek(self, time_s: float, mode: str = 'precise') -> None:
        self.video.seek(time_s, mode)
        self.stream = self.video.stream()       # reset stream after seeking
        return

    def _iterate_stream(self):
        (frame, ) = next(self.stream)
        frame = torch.squeeze(frame, 0)
        return frame

    def __next__(self) -> torch.Tensor:
        frame = self._iterate_stream()
        return frame

    def seek_and_get(self, frame_index: int) -> torch.Tensor:
        start = frame_index / self.fps
        self.seek(start, 'precise')
        frame = self._iterate_stream()
        return frame


def main():
    # Test a video with zero start-time
    video_path = 'source.mp4'

    vr1 = TorchaudioWrapper(video_path)
    vr2 = TorchaudioWrapper(video_path)

    print(vr1.fps)

    for i in range(len(vr1)):
        frame2 = next(vr2)
        frame1 = vr1.seek_and_get(i)
        assert torch.allclose(frame1, frame2), f'Test failed at frame {i}!'

    print('Test succeeded!')

    # Test a video with non-zero start-time
    video_path = 'test.mp4'

    vr1 = TorchaudioWrapper(video_path)
    vr2 = TorchaudioWrapper(video_path)

    print(vr1.fps)

    for i in range(len(vr1)):
        frame2 = next(vr2)
        frame1 = vr1.seek_and_get(i)
        assert torch.allclose(frame1, frame2), f'Test failed at frame {i}!'

    print('Test succeeded!')


if __name__ == '__main__':
    main()

The start_time_stamp of source.mp4 is zero and we can see that the seek functionality could seek to the correct frame by seeking to the time_stamp = (frame_index / fps), i.e. the first part succeeds. Then we use the command ffmpeg -i tmp/test_bug/source.mp4 -output_ts_offset 0.033333 -c copy tmp/test_bug/test.mp4 to generate test.mp4 from source.mp4. test.mp4 is exactly the same as source.mp4 except that the former has a non-zero start_time_stamp. However, the seek method of StreamReader returns a different frame and fails the second part of the test script.

I believe this behavior is not desired because a typical user of a video will not be aware of the value of the start_time_stamp. The same call of the seek method may return two different frames, causing unexpected misalignment problems. I tried another Video Reader, the Decord, and it could handle this issue correctly and always return the same frame whether the start_time_stamp is zero or not.

It would be highly appreciated if someone could further investigate this issue.

source.mp4
test.mp4

Versions

Collecting environment information...
PyTorch version: 2.4.0
Is debug build: False
CUDA used to build PyTorch: None
ROCM used to build PyTorch: N/A

OS: Ubuntu 20.04.6 LTS (x86_64)
GCC version: (Ubuntu 9.4.0-1ubuntu1~20.04.2) 9.4.0
Clang version: Could not collect
CMake version: Could not collect
Libc version: glibc-2.31

Python version: 3.10.14 (main, May  6 2024, 19:42:50) [GCC 11.2.0] (64-bit runtime)
Python platform: Linux-5.15.0-116-generic-x86_64-with-glibc2.31
Is CUDA available: False
CUDA runtime version: No CUDA
CUDA_MODULE_LOADING set to: N/A
GPU models and configuration: No CUDA
Nvidia driver version: No CUDA
cuDNN version: No CUDA
HIP runtime version: N/A
MIOpen runtime version: N/A
Is XNNPACK available: True

CPU:
Architecture:                         x86_64
CPU op-mode(s):                       32-bit, 64-bit
Byte Order:                           Little Endian
Address sizes:                        39 bits physical, 48 bits virtual
CPU(s):                               12
On-line CPU(s) list:                  0-11
Thread(s) per core:                   2
Core(s) per socket:                   6
Socket(s):                            1
NUMA node(s):                         1
Vendor ID:                            GenuineIntel
CPU family:                           6
Model:                                158
Model name:                           Intel(R) Core(TM) i7-8750H CPU @ 2.20GHz
Stepping:                             10
CPU MHz:                              2200.000
CPU max MHz:                          4100.0000
CPU min MHz:                          800.0000
BogoMIPS:                             4399.99
Virtualization:                       VT-x
L1d cache:                            192 KiB
L1i cache:                            192 KiB
L2 cache:                             1.5 MiB
L3 cache:                             9 MiB
NUMA node0 CPU(s):                    0-11
Vulnerability Gather data sampling:   Mitigation; Microcode
Vulnerability Itlb multihit:          KVM: Mitigation: VMX disabled
Vulnerability L1tf:                   Mitigation; PTE Inversion; VMX conditional cache flushes, SMT vulnerable
Vulnerability Mds:                    Mitigation; Clear CPU buffers; SMT vulnerable
Vulnerability Meltdown:               Mitigation; PTI
Vulnerability Mmio stale data:        Mitigation; Clear CPU buffers; SMT vulnerable
Vulnerability Reg file data sampling: Not affected
Vulnerability Retbleed:               Mitigation; IBRS
Vulnerability Spec rstack overflow:   Not affected
Vulnerability Spec store bypass:      Mitigation; Speculative Store Bypass disabled via prctl and seccomp
Vulnerability Spectre v1:             Mitigation; usercopy/swapgs barriers and __user pointer sanitization
Vulnerability Spectre v2:             Mitigation; IBRS; IBPB conditional; STIBP conditional; RSB filling; PBRSB-eIBRS Not affected; BHI Not affected
Vulnerability Srbds:                  Mitigation; Microcode
Vulnerability Tsx async abort:        Not affected
Flags:                                fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc art arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc cpuid aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb invpcid_single pti ssbd ibrs ibpb stibp tpr_shadow vnmi flexpriority ept vpid ept_ad fsgsbase tsc_adjust sgx bmi1 avx2 smep bmi2 erms invpcid mpx rdseed adx smap clflushopt intel_pt xsaveopt xsavec xgetbv1 xsaves dtherm ida arat pln pts hwp hwp_notify hwp_act_window hwp_epp sgx_lc md_clear flush_l1d arch_capabilities

Versions of relevant libraries:
[pip3] flake8==7.1.1
[pip3] mypy==1.11.1
[pip3] mypy-extensions==1.0.0
[pip3] numpy==1.26.4
[pip3] torch==2.4.0
[pip3] torchaudio==2.4.0
[pip3] torchvision==0.19.0
[conda] blas                      1.0                         mkl  
[conda] cpuonly                   2.0                           0    pytorch
[conda] libjpeg-turbo             2.0.0                h9bf148f_0    pytorch
[conda] mkl                       2023.1.0         h213fc3f_46344  
[conda] mkl-fft                   1.3.8                    pypi_0    pypi
[conda] mkl-random                1.2.4                    pypi_0    pypi
[conda] mkl-service               2.4.0                    pypi_0    pypi
[conda] mkl_fft                   1.3.8           py310h5eee18b_0  
[conda] mkl_random                1.2.4           py310hdb19cb5_0  
[conda] numpy                     1.26.4                   pypi_0    pypi
[conda] numpy-base                1.26.4          py310hb5e798b_0  
[conda] pytorch                   2.4.0              py3.10_cpu_0    pytorch
[conda] pytorch-mutex             1.0                         cpu    pytorch
[conda] torch                     2.4.0                    pypi_0    pypi
[conda] torchaudio                2.4.0                    pypi_0    pypi
[conda] torchvision               0.19.0                   pypi_0    pypi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant