PyNvVideoCodec 2.2.1__cp312-cp312-win_arm64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. PyNvVideoCodec/PyNvVideoCodec_121.cp312-win_arm64.pyd +0 -0
  2. PyNvVideoCodec/PyNvVideoCodec_130.cp312-win_arm64.pyd +0 -0
  3. PyNvVideoCodec/VersionCheck.cp312-win_arm64.pyd +0 -0
  4. PyNvVideoCodec/__init__.py +251 -0
  5. PyNvVideoCodec/avformat-62.dll +0 -0
  6. PyNvVideoCodec/avutil-60.dll +0 -0
  7. PyNvVideoCodec/decoders/SimpleDecoder.py +273 -0
  8. PyNvVideoCodec/decoders/ThreadedDecoder.py +129 -0
  9. PyNvVideoCodec/decoders/__init__.py +22 -0
  10. PyNvVideoCodec/transcoder/Transcoder.py +55 -0
  11. PyNvVideoCodec/transcoder/__init__.py +22 -0
  12. benchmarks/cached_decoder_benchmark.py +813 -0
  13. benchmarks/frame_sampling_benchmark.py +765 -0
  14. benchmarks/requirements.txt +52 -0
  15. benchmarks/segmented_transcode_benchmark.py +1546 -0
  16. benchmarks/setup_pycuda_win_arm64.bat +531 -0
  17. pynvvideocodec-2.2.1.data/data/external/ffmpeg/readme.txt +39 -0
  18. pynvvideocodec-2.2.1.data/data/external/ffmpeg/src/ffmpeg-8.1.2.tar.xz +0 -0
  19. pynvvideocodec-2.2.1.dist-info/METADATA +97 -0
  20. pynvvideocodec-2.2.1.dist-info/RECORD +63 -0
  21. pynvvideocodec-2.2.1.dist-info/WHEEL +5 -0
  22. pynvvideocodec-2.2.1.dist-info/licenses/LICENSE.txt +22 -0
  23. pynvvideocodec-2.2.1.dist-info/licenses/NOTICES.txt +167 -0
  24. pynvvideocodec-2.2.1.dist-info/top_level.txt +3 -0
  25. samples/advanced/decode.py +173 -0
  26. samples/advanced/decode_from_memory_buffer.py +204 -0
  27. samples/advanced/decode_perf.py +299 -0
  28. samples/advanced/decode_reconfigure.py +184 -0
  29. samples/advanced/decode_sei_msg.py +193 -0
  30. samples/advanced/decode_with_cuda_control.py +214 -0
  31. samples/advanced/decode_with_low_latency.py +183 -0
  32. samples/advanced/encode_config.json +12 -0
  33. samples/advanced/encode_config_lowlatency.json +13 -0
  34. samples/advanced/encode_perf.py +338 -0
  35. samples/advanced/encode_reconfigure.py +211 -0
  36. samples/advanced/encode_sei_msg.py +188 -0
  37. samples/advanced/simple_decode_from_memory.py +151 -0
  38. samples/advanced/simple_decode_stats.py +179 -0
  39. samples/advanced/transcode.py +288 -0
  40. samples/basic/create_video_segments.py +187 -0
  41. samples/basic/encode.py +574 -0
  42. samples/basic/segments.txt +3 -0
  43. samples/basic/simple_decode_sampling.py +182 -0
  44. samples/basic/transcode_config.json +6 -0
  45. samples/jupyter/ReconfigureDecoder.png +0 -0
  46. samples/jupyter/SimpleDecoderAPIs.png +0 -0
  47. samples/jupyter/ThreadedDecoder.png +0 -0
  48. samples/jupyter/coco_classes.pickle +0 -0
  49. samples/jupyter/face_protect_tutorial.ipynb +881 -0
  50. samples/jupyter/object_detection_tutorial.ipynb +781 -0
  51. samples/jupyter/simple_decode_tutorial.ipynb +674 -0
  52. samples/requirements.txt +84 -0
  53. samples/setup_pycuda_win_arm64.bat +531 -0
  54. samples/utils/Utils.py +405 -0
  55. samples/utils/__init__.py +36 -0
  56. samples/utils/decode_parser.py +642 -0
  57. samples/utils/decode_stats_writer.py +177 -0
  58. samples/utils/encode_parallel_utils.py +174 -0
  59. samples/utils/encode_parser.py +379 -0
  60. samples/utils/frame_utils.py +89 -0
  61. samples/utils/sei_message_parser.py +223 -0
  62. samples/utils/sei_parser.py +223 -0
  63. samples/utils/transcode_parser.py +218 -0
@@ -0,0 +1,188 @@
1
+ # This copyright notice applies to this file only
2
+ #
3
+ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
4
+ # SPDX-License-Identifier: MIT
5
+ #
6
+ # Permission is hereby granted, free of charge, to any person obtaining a
7
+ # copy of this software and associated documentation files (the "Software"),
8
+ # to deal in the Software without restriction, including without limitation
9
+ # the rights to use, copy, modify, merge, publish, distribute, sublicense,
10
+ # and/or sell copies of the Software, and to permit persons to whom the
11
+ # Software is furnished to do so, subject to the following conditions:
12
+ #
13
+ # The above copyright notice and this permission notice shall be included in
14
+ # all copies or substantial portions of the Software.
15
+ #
16
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19
+ # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21
+ # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
22
+ # DEALINGS IN THE SOFTWARE.
23
+
24
+ '''
25
+ This sample demonstrates SEI (Supplemental Enhancement Information) message insertion during encoding.
26
+ It shows how to:
27
+ 1. Create and format SEI messages
28
+ 2. Insert SEI data into the encoded bitstream
29
+ 3. Handle codec-specific SEI types
30
+ 4. Manage message timing and placement
31
+
32
+ SEI messages are additional data embedded in video streams that provide supplementary information:
33
+ - HDR/Display Metadata: Color volume, light levels, and transfer characteristics for HDR content
34
+ - Timecode Data: Frame timing and sequence information
35
+ - Custom Metadata: User-defined data for application-specific needs
36
+
37
+ Common Use Cases:
38
+ - Video Playback: HDR display configuration and color management
39
+ - Content Creation: Frame accurate editing and post-processing
40
+ - Broadcast: Timing synchronization and content identification
41
+ - Custom Applications: Embedding application-specific metadata in the video stream
42
+
43
+ Usage:
44
+ python encode_sei_msg.py -i <input_file> -s <size> [options]
45
+
46
+ Example:
47
+ python encode_sei_msg.py -i input.yuv -o output.h264 -s 1920x1080
48
+
49
+ Arguments:
50
+ -i: Raw input video file
51
+ -o: Output encoded file (optional, default: <input_name>.<codec>)
52
+ -s: Frame size (e.g., 1920x1080)
53
+ -if: Input format (default: NV12)
54
+ -f: Number of frames (default: all)
55
+ -g: GPU ID (default: 0)
56
+ -c: Output codec (h264/hevc/av1); overrides codec in JSON config
57
+ -json: Encoder config file (controls codec, fps, gop, preset, rc, bitrate, etc.)
58
+
59
+ '''
60
+
61
+ import PyNvVideoCodec as nvc
62
+ import sys
63
+ import os
64
+ from os.path import dirname, abspath
65
+
66
+ # Add the parent directory to Python path in a way that works from any working directory
67
+ current_dir = dirname(abspath(__file__))
68
+ parent_dir = dirname(current_dir)
69
+ if parent_dir not in sys.path:
70
+ sys.path.append(parent_dir)
71
+
72
+ # Import utilities for GPU buffer mode
73
+ try:
74
+ from utils.Utils import AppFrame, FetchCPUFrame, FetchGPUFrame
75
+ GPU_UTILS_AVAILABLE = True
76
+ except ImportError:
77
+ GPU_UTILS_AVAILABLE = False
78
+ print("Warning: Utils module not found. GPU buffer mode will be disabled.")
79
+
80
+ from utils.encode_parser import parse_sei_encode_args
81
+ SEI_MESSAGE_1 = [0xdc, 0x45, 0xe9, 0xbd, 0xe6, 0xd9, 0x48, 0xb7, 0x96, 0x2c, 0xd8, 0x20, 0xd9, 0x23, 0xee, 0xef]
82
+ SEI_MESSAGE_2 = [0x12, 0x67, 0x56, 0xda, 0xef, 0x99, 0x00, 0xbb, 0x6a, 0xc4, 0xd8, 0x10, 0xf9, 0xe3, 0x3e, 0x8f]
83
+
84
+
85
+ def encode_with_sei_msg(gpu_id, dec_file_path, enc_file_path, width, height, fmt, config_params, frame_count=0):
86
+ """
87
+ Encode frames with SEI message insertion into the bitstream using CUDA device buffers as input.
88
+
89
+ This function reads image data from a file and loads it to CUDA input buffers using FetchGPUFrame().
90
+ The encoder copies the CUDA buffers and SEI message data and submits them to NVENC hardware for encoding.
91
+ Video memory buffer is allocated to get the NVENC hardware output, which is then copied to host memory
92
+ for file storage.
93
+
94
+ Parameters:
95
+ gpu_id (int): Ordinal of GPU to use [Parameter not in use]
96
+ dec_file_path (str): Path to file to be decoded
97
+ enc_file_path (str): Path to output file for encoded frames
98
+ width (int): Width of encoded frame
99
+ height (int): Height of encoded frame
100
+ fmt (str): Surface format string in uppercase (e.g., "NV12")
101
+ config_params (dict): Key-value pairs providing fine-grained control on encoding
102
+
103
+ Returns:
104
+ None
105
+
106
+ Example:
107
+ >>> encode(0, "input.yuv", "output.h264", 1920, 1080, "NV12", {"codec": "h264"})
108
+ Encode 1080p NV12 raw YUV into elementary bitstream using H.264 codec with SEI messages
109
+ """
110
+ try:
111
+ # Determine SEI type based on codec
112
+ if config_params["codec"] in ["hevc", "h264"]:
113
+ sei_info = {"sei_type": 5}
114
+ elif config_params["codec"] == "av1":
115
+ sei_info = {"sei_type": 6}
116
+ else:
117
+ raise ValueError(f"Unsupported codec: {config_params['codec']}")
118
+
119
+ # Create SEI messages list
120
+ sei_messages = [(sei_info, SEI_MESSAGE_1), (sei_info, SEI_MESSAGE_2)]
121
+
122
+ with open(dec_file_path, "rb") as decFile, open(enc_file_path, "wb") as encFile:
123
+ # Create encoder object
124
+ config_params["gpu_id"] = gpu_id
125
+ nvenc = nvc.CreateEncoder(width, height, fmt, False, **config_params)
126
+
127
+ # Create input frame list
128
+ input_frame_list = [AppFrame(width, height, fmt) for _ in range(1, 5)]
129
+
130
+ # Process frames
131
+ # Calculate total available frames from file size
132
+ file_size = os.path.getsize(dec_file_path)
133
+ available_frames = file_size // input_frame_list[0].frameSize
134
+
135
+ # Determine frames to process
136
+ frames_to_process = frame_count if frame_count > 0 else available_frames
137
+ frames_to_process = min(frames_to_process, available_frames)
138
+
139
+ print(f"File contains {available_frames} frames, processing {frames_to_process} frames")
140
+
141
+ for input_gpu_frame in FetchGPUFrame(
142
+ input_frame_list,
143
+ FetchCPUFrame(decFile, input_frame_list[0].frameSize),
144
+ frames_to_process
145
+ ):
146
+ packets = nvenc.Encode(input_gpu_frame, 0, sei_messages)
147
+ encFile.write(
148
+ bytearray(b"".join(bytes(p["data"]) for p in packets))
149
+ )
150
+
151
+ # Flush encoder queue
152
+ flush_packets = nvenc.EndEncode()
153
+ encFile.write(bytearray(b"".join(bytes(p["data"]) for p in flush_packets)))
154
+
155
+ print(f"Encoded frames written to {enc_file_path} with SEI messages")
156
+
157
+ except nvc.PyNvVCExceptionUnsupported as e:
158
+ print(f"CreateEncoder failure: {e}")
159
+ except Exception as e:
160
+ print(f"An unexpected error occurred: {e}")
161
+
162
+
163
+ if __name__ == "__main__":
164
+ args = parse_sei_encode_args(
165
+ "This sample application illustrates encoding of frames with SEI message insertion."
166
+ )
167
+
168
+ print("=" * 60)
169
+ print("Configuration:")
170
+ print(f"Input: {args.raw_file_path}")
171
+ print(f"Output: {args.encoded_file_path}")
172
+ print(f"Size: {args.width}x{args.height}")
173
+ print(f"Format: {args.format}")
174
+ print(f"Codec: {args.codec}")
175
+ print(f"GPU ID: {args.gpu_id}")
176
+ print(f"Frame count: {args.frame_count if args.frame_count > 0 else 'All frames'}")
177
+ print("=" * 60)
178
+
179
+ encode_with_sei_msg(
180
+ args.gpu_id,
181
+ args.raw_file_path.as_posix(),
182
+ args.encoded_file_path.as_posix(),
183
+ args.width,
184
+ args.height,
185
+ args.format,
186
+ args.config,
187
+ args.frame_count
188
+ )
@@ -0,0 +1,151 @@
1
+ # This copyright notice applies to this file only
2
+ #
3
+ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
4
+ # SPDX-License-Identifier: MIT
5
+ #
6
+ # Permission is hereby granted, free of charge, to any person obtaining a
7
+ # copy of this software and associated documentation files (the "Software"),
8
+ # to deal in the Software without restriction, including without limitation
9
+ # the rights to use, copy, modify, merge, publish, distribute, sublicense,
10
+ # and/or sell copies of the Software, and to permit persons to whom the
11
+ # Software is furnished to do so, subject to the following conditions:
12
+ #
13
+ # The above copyright notice and this permission notice shall be included in
14
+ # all copies or substantial portions of the Software.
15
+ #
16
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19
+ # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21
+ # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
22
+ # DEALINGS IN THE SOFTWARE.
23
+
24
+
25
+ '''
26
+ This sample demonstrates that SimpleDecoder can decode directly from in-memory
27
+ sources -- no temporary file required. It showcases every supported in-memory
28
+ input type in one place:
29
+
30
+ 1. bytes -- an immutable in-memory buffer
31
+ 2. bytearray -- a mutable in-memory buffer
32
+ 3. memoryview -- a zero-copy view over a buffer
33
+ 4. BinaryIO -- any seekable file-like object (file handle, io.BytesIO,
34
+ tarfile member, S3/HTTP range-reader, etc.)
35
+
36
+ There are two distinct mechanisms under the hood:
37
+
38
+ * bytes / bytearray / memoryview ("bytestream"):
39
+ The entire buffer is copied once into native memory, then FFmpeg reads
40
+ from it. Fast per-read (no Python callbacks), uses memory proportional
41
+ to the file size. Best when the whole clip is already in RAM.
42
+
43
+ * BinaryIO stream:
44
+ The data stays in the source; FFmpeg pulls only the bytes it needs
45
+ (container headers + the packets for the requested frames) on demand by
46
+ calling the object's read()/seek() methods. No full-file copy. Best for
47
+ large videos or remote/archived sources (tar, S3, HTTP).
48
+
49
+ All input types are fully SEEKABLE and support the complete SimpleDecoder API:
50
+ len(), random access (decoder[i]), slicing, out-of-order batch access
51
+ (get_batch_frames_by_index), seek_to_index, and stream metadata.
52
+
53
+ This is the key difference from decode_from_memory_buffer.py, which uses the
54
+ older streaming (non-seekable) callback demuxer and only supports sequential
55
+ decode.
56
+
57
+ Usage: python simple_decode_from_memory.py -i <input_file>
58
+ Example: python simple_decode_from_memory.py -i input.mp4
59
+
60
+ Arguments:
61
+ -i: Input video file (container format such as MP4, MKV, etc.)
62
+ -g: GPU ID to use (default: 0)
63
+ '''
64
+
65
+ import argparse
66
+ import io
67
+
68
+ import PyNvVideoCodec as nvc
69
+
70
+
71
+ def exercise_decoder(decoder, source_label):
72
+ """Run the full seekable SimpleDecoder contract against any in-memory source."""
73
+ total_frames = len(decoder)
74
+ metadata = decoder.get_stream_metadata()
75
+
76
+ print(f" Source type : {source_label}")
77
+ print(f" Total frames : {total_frames}")
78
+ print(f" Resolution : {metadata.width}x{metadata.height}")
79
+ print(f" Codec : {metadata.codec_name}")
80
+ print(f" Average FPS : {metadata.average_fps:.2f}")
81
+ print(f" Duration : {metadata.duration:.3f}s")
82
+
83
+ # Random access via decoder[i]: fetch the first and last frame from the
84
+ # in-memory source.
85
+ # NOTE: the default output is NATIVE (NV12 for 8-bit 4:2:0). An NV12 frame is
86
+ # returned as a single 2D buffer of shape (height * 3 / 2, width): the luma
87
+ # plane (height x width) stacked on top of the interleaved chroma plane
88
+ # (height/2 x width). So a 1920x1080 picture has buffer shape (1620, 1920) --
89
+ # that is the NV12 layout, not a different resolution. Use
90
+ # output_color_type=nvc.OutputColorType.RGB for a (height, width, 3) image shape.
91
+ for idx in [0, total_frames - 1]:
92
+ frame = decoder[idx]
93
+ print(f" decoder[{idx:>3}] : NV12 buffer shape={tuple(frame.shape)} "
94
+ f"(picture {metadata.width}x{metadata.height})")
95
+
96
+
97
+ def main():
98
+ parser = argparse.ArgumentParser(
99
+ description="Demonstrates SimpleDecoder decoding from bytes, bytearray, "
100
+ "memoryview, and BinaryIO stream inputs."
101
+ )
102
+ parser.add_argument("-i", "--input", required=True, help="Input video file path")
103
+ parser.add_argument("-g", "--gpu_id", type=int, default=0, help="GPU ID (default: 0)")
104
+ args = parser.parse_args()
105
+
106
+ # Read the file once; we reuse the raw bytes to build each input type.
107
+ print(f"Reading {args.input} into memory...")
108
+ with open(args.input, "rb") as f:
109
+ raw = f.read()
110
+ print(f" Buffer size: {len(raw) / (1024 * 1024):.2f} MiB\n")
111
+
112
+ # ------------------------------------------------------------------
113
+ # Group 1: bytestream inputs (full buffer copied into native memory)
114
+ # ------------------------------------------------------------------
115
+ print("=" * 64)
116
+ print("bytestream inputs (whole buffer copied into native memory)")
117
+ print("=" * 64)
118
+
119
+ print("\n--- bytes ---")
120
+ exercise_decoder(nvc.SimpleDecoder(raw, gpu_id=args.gpu_id), "bytes")
121
+
122
+ print("\n--- bytearray ---")
123
+ exercise_decoder(nvc.SimpleDecoder(bytearray(raw), gpu_id=args.gpu_id), "bytearray")
124
+
125
+ print("\n--- memoryview ---")
126
+ exercise_decoder(nvc.SimpleDecoder(memoryview(raw), gpu_id=args.gpu_id), "memoryview")
127
+
128
+ # ------------------------------------------------------------------
129
+ # Group 2: BinaryIO stream inputs (bytes pulled on demand, no copy)
130
+ # ------------------------------------------------------------------
131
+ print("\n" + "=" * 64)
132
+ print("BinaryIO stream inputs (bytes pulled on demand, no full copy)")
133
+ print("=" * 64)
134
+
135
+ # A file handle is itself a BinaryIO object -- decode straight from it.
136
+ print("\n--- open(path, 'rb') file stream ---")
137
+ with open(args.input, "rb") as file_stream:
138
+ exercise_decoder(nvc.SimpleDecoder(file_stream, gpu_id=args.gpu_id),
139
+ "file handle (BinaryIO)")
140
+
141
+ # io.BytesIO wraps an in-memory buffer as a seekable stream.
142
+ print("\n--- io.BytesIO stream ---")
143
+ exercise_decoder(nvc.SimpleDecoder(io.BytesIO(raw), gpu_id=args.gpu_id),
144
+ "io.BytesIO (BinaryIO)")
145
+
146
+ print("\nDone. SimpleDecoder decoded the same video from "
147
+ "bytes, bytearray, memoryview, and BinaryIO streams.")
148
+
149
+
150
+ if __name__ == "__main__":
151
+ main()
@@ -0,0 +1,179 @@
1
+ # This copyright notice applies to this file only
2
+ #
3
+ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
4
+ # SPDX-License-Identifier: MIT
5
+ #
6
+ # Permission is hereby granted, free of charge, to any person obtaining a
7
+ # copy of this software and associated documentation files (the "Software"),
8
+ # to deal in the Software without restriction, including without limitation
9
+ # the rights to use, copy, modify, merge, publish, distribute, sublicense,
10
+ # and/or sell copies of the Software, and to permit persons to whom the
11
+ # Software is furnished to do so, subject to the following conditions:
12
+ #
13
+ # The above copyright notice and this permission notice shall be included in
14
+ # all copies or substantial portions of the Software.
15
+ #
16
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19
+ # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21
+ # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
22
+ # DEALINGS IN THE SOFTWARE.
23
+
24
+
25
+
26
+ '''
27
+ This sample demonstrates how to extract and analyze decode statistics using SimpleDecoder
28
+ in PyNvVideoCodec. It shows how to:
29
+ 1. Enable statistics collection with SimpleDecoder
30
+ 2. Extract statistics from decoded frames
31
+ 3. Parse and analyze the statistics
32
+ 4. Write formatted results to a file
33
+
34
+
35
+ Core module for handling decode statistics.
36
+
37
+ This module provides functionality for extracting and analyzing low-level video decoding
38
+ statistics from H.264/H.265 streams. The following statistics are collected and analyzed:
39
+
40
+ 1. QP (Quantization Parameter) Analysis:
41
+ - Average, min, max QP values per frame
42
+ - Indicates compression level and quality trade-offs
43
+ - Higher QP = more compression, potentially lower quality
44
+
45
+ 2. CU (Coding Unit) Type Distribution:
46
+ - INTRA: Spatial prediction (current frame only)
47
+ - INTER: Temporal prediction (motion compensation)
48
+ - SKIP: Copy from reference without residual
49
+ - PCM: Uncompressed raw pixel values
50
+
51
+ 3. Motion Vector Statistics:
52
+ - MV0: Primary motion vectors (L0 reference)
53
+ - MV1: Secondary motion vectors (L1 reference, B-frames)
54
+ - Magnitude analysis for temporal complexity assessment
55
+
56
+ 4. Macroblock Details:
57
+ - Per-block encoding decisions and parameters
58
+ - Motion vector coordinates and directions
59
+ - QP values and prediction types for debugging
60
+
61
+ These statistics are valuable for:
62
+ - Video quality analysis
63
+ - Encoder behavior understanding
64
+ - Performance optimization
65
+ - Debugging encoding/decoding issues
66
+
67
+ Usage: python single_decode_stats.py -i <input_video_file> -p <output_stats_file> -d <use_device_memory>
68
+ Example: python single_decode_stats.py -i test_video.mp4 -p test_video_stats.txt -d 0
69
+
70
+ Arguments:
71
+ -i: Input video file
72
+ -p: Output file for statistics (default: <input_name>_stats.txt)
73
+ -d: Use device memory (1) or host memory (0) (default: 1)
74
+ -g: GPU ID to use (default: 0)
75
+
76
+ Note: For large videos, consider processing in segments to manage memory usage.
77
+ '''
78
+
79
+ import sys
80
+ import argparse
81
+ from pathlib import Path
82
+ import PyNvVideoCodec as nvc
83
+ from os.path import join, dirname, abspath
84
+
85
+ # Add the parent directory to Python path in a way that works from any working directory
86
+ current_dir = dirname(abspath(__file__))
87
+ parent_dir = dirname(current_dir)
88
+ if parent_dir not in sys.path:
89
+ sys.path.append(parent_dir)
90
+
91
+ # Import utilities for decoding
92
+ from utils.decode_parser import parse_stats_args
93
+ from utils.Utils import get_frame_data
94
+ from utils.decode_stats_writer import DecodeStatsWriter
95
+
96
+
97
+ def decode(gpu_id, enc_file_path, stats_file_path, use_device_memory, need_scanned_stream_metadata):
98
+ """
99
+ Function to decode media file, write decode statistics into output file.
100
+
101
+ Parameters:
102
+ gpu_id (int): Ordinal of GPU to use
103
+ enc_file_path (str): Path to file to be decoded
104
+ stats_file_path (str): Path to output file for decode statistics
105
+ use_device_memory (int): If set to 1, output decoded frame is CUDeviceptr wrapped in CUDA Array Interface
106
+ need_scanned_stream_metadata (bool): If True, scan stream for detailed metadata (keyframe locations, etc.)
107
+
108
+ Returns:
109
+ None
110
+ """
111
+
112
+ with open(stats_file_path, "w", newline='\n') as stats_file:
113
+ try:
114
+ # Initialize decoder
115
+ simple_decoder = nvc.SimpleDecoder(
116
+ enc_file_path,
117
+ need_scanned_stream_metadata=need_scanned_stream_metadata,
118
+ use_device_memory=use_device_memory,
119
+ gpu_id=gpu_id,
120
+ enableDecodeStats=True
121
+ )
122
+
123
+ # Get metadata and initialize stats writer
124
+ metadata = simple_decoder.get_stream_metadata()
125
+ stats_writer = DecodeStatsWriter(stats_file)
126
+
127
+ stats_count = 0
128
+ decoded_frame_count = 0
129
+
130
+ # Process frames
131
+ for decoded_frame in simple_decoder:
132
+ if hasattr(decoded_frame, 'decode_stats_size') and decoded_frame.decode_stats_size > 0:
133
+ try:
134
+ parsed_stats = decoded_frame.ParseDecodeStats()
135
+ if len(parsed_stats.get("qp_luma", [])) > 0:
136
+ stats_count += 1
137
+ stats_writer.write_frame_stats(
138
+ decoded_frame_count,
139
+ parsed_stats
140
+ )
141
+ except Exception as e:
142
+ print(f"Frame {decoded_frame_count}: API parsing failed: {e}")
143
+
144
+ decoded_frame_count += 1
145
+
146
+ # Print summary
147
+ print(f"Decoded {decoded_frame_count} frames")
148
+ if stats_count == 0:
149
+ print(f"Decode statistics not found")
150
+ else:
151
+ print(f"Decode statistics of {stats_count} frames written to: {stats_file_path}\n")
152
+
153
+ except nvc.PyNvVCExceptionUnsupported as e:
154
+ print(f"CreateDecoder failure: {e}")
155
+ except Exception as e:
156
+ print(f"An unexpected error occurred: {e}")
157
+
158
+ if __name__ == "__main__":
159
+ args = parse_stats_args(
160
+ "This sample application demonstrates decoding media files and extracting decode statistics. "
161
+ "Use -p to enable parsing and text output."
162
+ )
163
+
164
+ print("=" * 60)
165
+ print("Configuration:")
166
+ print(f"Input: {args.encoded_file_path}")
167
+ print(f"Stats Output: {args.stats_file_path}")
168
+ print(f"GPU ID: {args.gpu_id}")
169
+ print(f"Use Device Memory: {args.use_device_memory}")
170
+ print(f"Need Scanned Stream Metadata: {args.need_scanned_stream_metadata}")
171
+ print("=" * 60)
172
+
173
+ decode(
174
+ args.gpu_id,
175
+ args.encoded_file_path,
176
+ args.stats_file_path,
177
+ args.use_device_memory,
178
+ args.need_scanned_stream_metadata
179
+ )