Debian Codegraph @

examples/basics/hw_decode.py

raw
1 import os
2 import time
3
4 import av
5 import av.datasets
6 from av.codec.hwaccel import HWAccel, hwdevices_available
7
8 # What accelerator to use.
9 # Recommendations:
10 # Windows:
11 # - d3d11va (Direct3D 11)
12 # * available with built-in ffmpeg in PyAV binary wheels, and gives access to
13 # all decoders, but performance may not be as good as vendor native interfaces.
14 # - cuda (NVIDIA NVDEC), qsv (Intel QuickSync)
15 # * may be faster than d3d11va, but requires custom ffmpeg built with those libraries.
16 # Linux (all options require custom FFmpeg):
17 # - vaapi (Intel, AMD)
18 # - cuda (NVIDIA)
19 # Mac:
20 # - videotoolbox
21 # * available with built-in ffmpeg in PyAV binary wheels, and gives access to
22 # all accelerators available on Macs. This is the only option on MacOS.
23
24 HW_DEVICE = os.environ["HW_DEVICE"] if "HW_DEVICE" in os.environ else None
25
26 if "TEST_FILE_PATH" in os.environ:
27 test_file_path = os.environ["TEST_FILE_PATH"]
28 else:
29 test_file_path = av.datasets.curated(
30 "pexels/time-lapse-video-of-night-sky-857195.mp4"
31 )
32
33 if HW_DEVICE is None:
34 print(f"Please set HW_DEVICE. Options are: {hwdevices_available()}")
35 exit()
36
37 assert HW_DEVICE in hwdevices_available(), f"{HW_DEVICE} not available."
38
39 print("Decoding in software (auto threading)...")
40
41 container = av.open(test_file_path)
42
43 container.streams.video[0].thread_type = "AUTO"
44
45 start_time = time.time()
46 frame_count = 0
47 for packet in container.demux(video=0):
48 for _ in packet.decode():
49 frame_count += 1
50
51 sw_time = time.time() - start_time
52 sw_fps = frame_count / sw_time
53 assert frame_count == container.streams.video[0].frames
54 container.close()
55
56 print(
57 f"Decoded with software in {sw_time:.2f}s ({sw_fps:.2f} fps).\n"
58 f"Decoding with {HW_DEVICE}"
59 )
60
61 hwaccel = HWAccel(device_type=HW_DEVICE, allow_software_fallback=False)
62
63 # Note the additional argument here.
64 container = av.open(test_file_path, hwaccel=hwaccel)
65
66 start_time = time.time()
67 frame_count = 0
68 for packet in container.demux(video=0):
69 for _ in packet.decode():
70 frame_count += 1
71
72 hw_time = time.time() - start_time
73 hw_fps = frame_count / hw_time
74 assert frame_count == container.streams.video[0].frames
75 container.close()
76
77 print(f"Decoded with {HW_DEVICE} in {hw_time:.2f}s ({hw_fps:.2f} fps).")