PyNvVideoCodec 2.2.1__cp313-cp313-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.cp313-win_arm64.pyd +0 -0
  2. PyNvVideoCodec/PyNvVideoCodec_130.cp313-win_arm64.pyd +0 -0
  3. PyNvVideoCodec/VersionCheck.cp313-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,379 @@
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
+ Helper module for parsing encoder command line arguments.
26
+
27
+ This module provides standardized argument parsing for encoder sample applications.
28
+ """
29
+
30
+ import argparse
31
+ from pathlib import Path
32
+ from os.path import join, dirname
33
+ import json
34
+ import PyNvVideoCodec as nvc
35
+
36
+ # Maximum frames for performance testing to avoid OOM
37
+ PERF_MAX_FRAMES = 1000
38
+
39
+ def add_encode_args(parser: argparse.ArgumentParser, enforce_frame_limit: bool = False) -> None:
40
+ """Add common encoder arguments to parser.
41
+
42
+ Args:
43
+ parser: The argument parser to add arguments to
44
+ enforce_frame_limit: If True, enforces max frame limit for perf testing
45
+ """
46
+ parser.add_argument(
47
+ "-g", "--gpu_id",
48
+ type=int,
49
+ default=0,
50
+ help="Check nvidia-smi for available GPUs. Default: 0"
51
+ )
52
+ parser.add_argument(
53
+ "-i", "--raw_file_path",
54
+ type=Path,
55
+ required=True,
56
+ help="Raw video file to encode"
57
+ )
58
+ parser.add_argument(
59
+ "-o", "--encoded_file_path",
60
+ type=Path,
61
+ help="Encoded video file (write to). Default: <input_file_name>.<codec>"
62
+ )
63
+ parser.add_argument(
64
+ "-s", "--size",
65
+ type=str,
66
+ required=True,
67
+ help="WidthxHeight of raw frame (e.g., 1920x1080)"
68
+ )
69
+ parser.add_argument(
70
+ "-if", "--format",
71
+ type=str,
72
+ default="NV12",
73
+ help="Format of input file. Default: NV12"
74
+ )
75
+ parser.add_argument(
76
+ "-c", "--codec",
77
+ type=str,
78
+ default=None,
79
+ choices=["h264", "hevc", "av1"],
80
+ help="Output codec (h264/hevc/av1). Overrides the codec in the JSON config file."
81
+ )
82
+ parser.add_argument(
83
+ "-json", "--config_file",
84
+ type=str,
85
+ default=join(dirname(dirname(__file__)), "advanced", "encode_config.json"),
86
+ help="Path of JSON config file (default: encode_config.json in samples directory)"
87
+ )
88
+ help_text = "Number of frames to encode (0 for all frames). Default: 0"
89
+ if enforce_frame_limit:
90
+ help_text = f"Number of frames to encode (0-{PERF_MAX_FRAMES}, required for perf testing). Default: {PERF_MAX_FRAMES}"
91
+
92
+ parser.add_argument(
93
+ "-f", "--frame_count",
94
+ type=int,
95
+ default=PERF_MAX_FRAMES if enforce_frame_limit else 0,
96
+ help=help_text
97
+ )
98
+
99
+ def add_parallel_args(parser: argparse.ArgumentParser) -> None:
100
+ """Add parallel processing arguments to parser."""
101
+ parser.add_argument(
102
+ "-m", "--mode",
103
+ type=str,
104
+ choices=["thread", "process"],
105
+ default="thread",
106
+ help="Parallel execution mode: 'thread' or 'process'"
107
+ )
108
+ parser.add_argument(
109
+ "-n", "--num_workers",
110
+ type=int,
111
+ default=1,
112
+ help="Number of parallel threads/processes. Default: 1"
113
+ )
114
+
115
+ def load_config(args) -> dict:
116
+ """Load and process encoder configuration from the JSON config file.
117
+
118
+ codec is resolved with CLI priority: if -c/--codec was given on the command
119
+ line it overrides the JSON value; otherwise the JSON codec (default: h264)
120
+ is used. fps and gop always come from the JSON config (fallbacks: 30/30).
121
+ All three are mirrored back onto ``args`` so downstream code can keep using
122
+ ``args.codec``/``args.fps``/``args.gop_size``.
123
+ The NVENC C++ binding reads the "gop" key from kwargs.
124
+ """
125
+ config = {}
126
+ if args.config_file:
127
+ with open(args.config_file) as jsonFile:
128
+ config = json.loads(jsonFile.read())
129
+ config["preset"] = config["preset"].upper()
130
+
131
+ json_codec = str(config.get("codec", "h264")).lower()
132
+ cli_codec = getattr(args, "codec", None)
133
+ codec = cli_codec.lower() if cli_codec else json_codec
134
+ args.codec = codec
135
+ config["codec"] = codec
136
+
137
+ fps = int(config.get("fps", 30))
138
+ args.fps = fps
139
+ config["fps"] = fps
140
+
141
+ gop = int(config.get("gop", 30))
142
+ args.gop_size = gop
143
+ config["gop"] = gop
144
+
145
+ config["gpu_id"] = args.gpu_id
146
+
147
+ args.format = args.format.upper()
148
+
149
+ width, height = map(int, args.size.split("x"))
150
+ args.width = width
151
+ args.height = height
152
+
153
+ if not hasattr(args, 'encoded_file_path') or args.encoded_file_path is None:
154
+ args.encoded_file_path = args.raw_file_path.with_suffix(f'.{args.codec}')
155
+
156
+ return config
157
+
158
+ def add_unified_args(parser: argparse.ArgumentParser) -> None:
159
+ """Add unified encoder specific arguments to parser."""
160
+ parser.add_argument(
161
+ "-m", "--buffer_mode",
162
+ type=str,
163
+ choices=["cpu", "gpu"],
164
+ default="gpu",
165
+ help="Buffer mode: 'cpu' for host memory buffers, 'gpu' for CUDA device buffers. Default: gpu"
166
+ )
167
+
168
+ def parse_perf_args(description: str = None) -> argparse.Namespace:
169
+ """Parse arguments for performance testing applications.
170
+
171
+ These apps require frame count limits to prevent OOM errors.
172
+ Note: No output file argument as perf apps only measure performance without file output.
173
+ """
174
+ parser = argparse.ArgumentParser(description=description)
175
+
176
+ # Add args manually without output file
177
+ parser.add_argument(
178
+ "-g", "--gpu_id",
179
+ type=int,
180
+ default=0,
181
+ help="Check nvidia-smi for available GPUs. Default: 0"
182
+ )
183
+ parser.add_argument(
184
+ "-i", "--raw_file_path",
185
+ type=Path,
186
+ required=True,
187
+ help="Raw video file to encode"
188
+ )
189
+ parser.add_argument(
190
+ "-s", "--size",
191
+ type=str,
192
+ required=True,
193
+ help="WidthxHeight of raw frame (e.g., 1920x1080)"
194
+ )
195
+ parser.add_argument(
196
+ "-if", "--format",
197
+ type=str,
198
+ default="NV12",
199
+ help="Format of input file. Default: NV12"
200
+ )
201
+ parser.add_argument(
202
+ "-c", "--codec",
203
+ type=str,
204
+ default=None,
205
+ choices=["h264", "hevc", "av1"],
206
+ help="Output codec (h264/hevc/av1). Overrides the codec in the JSON config file."
207
+ )
208
+ parser.add_argument(
209
+ "-json", "--config_file",
210
+ type=str,
211
+ default=join(dirname(dirname(__file__)), "advanced", "encode_config.json"),
212
+ help="Path of JSON config file (default: encode_config.json in samples directory)"
213
+ )
214
+ parser.add_argument(
215
+ "-f", "--frame_count",
216
+ type=int,
217
+ default=PERF_MAX_FRAMES,
218
+ help=f"Number of frames to encode (0-{PERF_MAX_FRAMES}, required for perf testing). Default: {PERF_MAX_FRAMES}"
219
+ )
220
+
221
+ add_parallel_args(parser)
222
+ args = parser.parse_args()
223
+
224
+ # Enforce frame limit for perf testing
225
+ if args.frame_count > PERF_MAX_FRAMES:
226
+ print(f"\nWarning: Requested {args.frame_count} frames exceeds limit. Using {PERF_MAX_FRAMES} frames.")
227
+ args.frame_count = PERF_MAX_FRAMES
228
+ elif args.frame_count <= 0:
229
+ args.frame_count = PERF_MAX_FRAMES
230
+
231
+ # Set encoded_file_path to None for perf apps (no output)
232
+ args.encoded_file_path = None
233
+
234
+ args.config = load_config(args)
235
+ return args
236
+
237
+
238
+ def parse_unified_args(description: str = None) -> argparse.Namespace:
239
+ """Parse arguments for unified encoding applications.
240
+
241
+ These apps support unlimited frame counts and both CPU/GPU buffer modes.
242
+ """
243
+ parser = argparse.ArgumentParser(description=description)
244
+ add_unified_args(parser)
245
+ add_encode_args(parser, enforce_frame_limit=False)
246
+ args = parser.parse_args()
247
+ args.config = load_config(args)
248
+ return args
249
+
250
+ def parse_sei_encode_args(description: str = None) -> argparse.Namespace:
251
+ """Parse arguments for SEI encoding applications.
252
+
253
+ These apps use GPU buffer mode only and support unlimited frame counts.
254
+ Note: No buffer mode argument as these apps only support GPU buffer mode.
255
+ """
256
+ parser = argparse.ArgumentParser(description=description)
257
+
258
+ # Add encode args manually without buffer mode
259
+ parser.add_argument(
260
+ "-g", "--gpu_id",
261
+ type=int,
262
+ default=0,
263
+ help="Check nvidia-smi for available GPUs. Default: 0"
264
+ )
265
+ parser.add_argument(
266
+ "-i", "--raw_file_path",
267
+ type=Path,
268
+ required=True,
269
+ help="Raw video file to encode"
270
+ )
271
+ parser.add_argument(
272
+ "-o", "--encoded_file_path",
273
+ type=Path,
274
+ help="Encoded video file (write to). Default: <input_file_name>.<codec>"
275
+ )
276
+ parser.add_argument(
277
+ "-s", "--size",
278
+ type=str,
279
+ required=True,
280
+ help="WidthxHeight of raw frame (e.g., 1920x1080)"
281
+ )
282
+ parser.add_argument(
283
+ "-if", "--format",
284
+ type=str,
285
+ default="NV12",
286
+ help="Format of input file. Default: NV12"
287
+ )
288
+ parser.add_argument(
289
+ "-c", "--codec",
290
+ type=str,
291
+ default=None,
292
+ choices=["h264", "hevc", "av1"],
293
+ help="Output codec (h264/hevc/av1). Overrides the codec in the JSON config file."
294
+ )
295
+ parser.add_argument(
296
+ "-json", "--config_file",
297
+ type=str,
298
+ default=join(dirname(dirname(__file__)), "advanced", "encode_config.json"),
299
+ help="Path of JSON config file (default: encode_config.json in samples directory)"
300
+ )
301
+ parser.add_argument(
302
+ "-f", "--frame_count",
303
+ type=int,
304
+ default=0,
305
+ help="Number of frames to encode (0 for all frames). Default: 0"
306
+ )
307
+
308
+ args = parser.parse_args()
309
+ args.config = load_config(args)
310
+ return args
311
+
312
+ def parse_reconfigure_encode_args(description: str = None) -> argparse.Namespace:
313
+ """Parse arguments for encoder reconfiguration applications.
314
+
315
+ These apps use GPU buffer mode only and support unlimited frame counts.
316
+ Note: No buffer mode argument as these apps only support GPU buffer mode.
317
+ """
318
+ parser = argparse.ArgumentParser(description=description)
319
+
320
+ # Add encode args without buffer mode
321
+ parser.add_argument(
322
+ "-g", "--gpu_id",
323
+ type=int,
324
+ default=0,
325
+ help="Check nvidia-smi for available GPUs. Default: 0"
326
+ )
327
+ parser.add_argument(
328
+ "-i", "--raw_file_path",
329
+ type=Path,
330
+ required=True,
331
+ help="Raw video file to encode"
332
+ )
333
+ parser.add_argument(
334
+ "-o", "--encoded_file_path",
335
+ type=Path,
336
+ help="Encoded video file (write to). Default: <input_file_name>.<codec>"
337
+ )
338
+ parser.add_argument(
339
+ "-s", "--size",
340
+ type=str,
341
+ required=True,
342
+ help="WidthxHeight of raw frame (e.g., 1920x1080)"
343
+ )
344
+ parser.add_argument(
345
+ "-if", "--format",
346
+ type=str,
347
+ default="NV12",
348
+ help="Format of input file. Default: NV12"
349
+ )
350
+ parser.add_argument(
351
+ "-c", "--codec",
352
+ type=str,
353
+ default=None,
354
+ choices=["h264", "hevc", "av1"],
355
+ help="Output codec (h264/hevc/av1). Overrides the codec in the JSON config file."
356
+ )
357
+ parser.add_argument(
358
+ "-json", "--config_file",
359
+ type=str,
360
+ default=join(dirname(dirname(__file__)), "advanced", "encode_config_lowlatency.json"),
361
+ help="Path of JSON config file (default: encode_config_lowlatency.json in samples directory)"
362
+ )
363
+ parser.add_argument(
364
+ "-f", "--frame_count",
365
+ type=int,
366
+ default=0,
367
+ help="Number of frames to encode (0 for all frames). Default: 0"
368
+ )
369
+ parser.add_argument(
370
+ "-tq", "--reconfigure_target_quality",
371
+ action="store_true",
372
+ help="Also reconfigure targetQuality when alternating bitrate (requires cq in config)"
373
+ )
374
+
375
+ args = parser.parse_args()
376
+ args.config = load_config(args)
377
+ return args
378
+
379
+
@@ -0,0 +1,89 @@
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
+ Helper module for frame and memory management in video encoding/decoding.
26
+ """
27
+
28
+ import mmap
29
+ import sys
30
+ import pycuda.driver as cuda
31
+
32
+ def get_frame_size(width: int, height: int, surface_format: str) -> int:
33
+ """
34
+ Calculate the size of a frame in bytes based on its dimensions and format.
35
+
36
+ Parameters:
37
+ width (int): Width of the frame
38
+ height (int): Height of the frame
39
+ surface_format (str): Format of the surface (e.g., "NV12", "ARGB", "YUV444")
40
+
41
+ Returns:
42
+ int: Size of the frame in bytes
43
+ """
44
+ if surface_format in ("ARGB", "ABGR"):
45
+ return width * height * 4
46
+ elif surface_format == "YUV444":
47
+ return width * height * 3
48
+ elif surface_format == "YUV420":
49
+ return int(width * height * 3 / 2)
50
+ elif surface_format == "P010":
51
+ return int(width * height * 3 / 2 * 2)
52
+ elif surface_format == "YUV444_16BIT":
53
+ return int(width * height * 3 * 2)
54
+ elif surface_format == "NV16":
55
+ return width * height * 2
56
+ elif surface_format == "P210":
57
+ return width * height * 2 * 2
58
+ else: # Default NV12
59
+ return int(width * height * 3 / 2)
60
+
61
+ def create_memory_map(file_handle, access_read=True) -> mmap.mmap:
62
+ """
63
+ Create a memory map for a file with cross-platform support.
64
+
65
+ Parameters:
66
+ file_handle: File object to memory map
67
+ access_read: If True, create read-only mapping, else read-write
68
+
69
+ Returns:
70
+ mmap.mmap: Memory mapped file object
71
+ """
72
+ if sys.platform == 'win32':
73
+ return mmap.mmap(file_handle.fileno(), 0, access=mmap.ACCESS_READ if access_read else mmap.ACCESS_WRITE)
74
+ else:
75
+ return mmap.mmap(file_handle.fileno(), 0, prot=mmap.PROT_READ if access_read else mmap.PROT_WRITE)
76
+
77
+ def allocate_device_memory(host_data) -> cuda.DeviceAllocation:
78
+ """
79
+ Allocate CUDA device memory and copy host data.
80
+
81
+ Parameters:
82
+ host_data: Data to copy to device
83
+
84
+ Returns:
85
+ cuda.DeviceAllocation: Allocated device memory with copied data
86
+ """
87
+ device_data = cuda.mem_alloc(len(host_data))
88
+ cuda.memcpy_htod(device_data, host_data)
89
+ return device_data
@@ -0,0 +1,223 @@
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
+ SEI message structures and parsing utilities.
26
+ """
27
+
28
+ import ctypes
29
+ import pickle
30
+ import os
31
+ from os.path import join, dirname, abspath
32
+ import PyNvVideoCodec as nvc
33
+
34
+ # Constants
35
+ MAX_CLOCK_TS = 3
36
+
37
+ class TIMECODESET(ctypes.Structure):
38
+ """Structure for time code set information."""
39
+ _fields_ = [
40
+ ("time_offset_value", ctypes.c_uint32), # unsigned int
41
+ ("n_frames", ctypes.c_uint16), # unsigned short
42
+ ("clock_timestamp_flag", ctypes.c_uint8), # unsigned char
43
+ ("units_field_based_flag", ctypes.c_uint8), # unsigned char
44
+ ("counting_type", ctypes.c_uint8), # unsigned char
45
+ ("full_timestamp_flag", ctypes.c_uint8), # unsigned char
46
+ ("discontinuity_flag", ctypes.c_uint8), # unsigned char
47
+ ("cnt_dropped_flag", ctypes.c_uint8), # unsigned char
48
+ ("seconds_value", ctypes.c_uint8), # unsigned char
49
+ ("minutes_value", ctypes.c_uint8), # unsigned char
50
+ ("hours_value", ctypes.c_uint8), # unsigned char
51
+ ("seconds_flag", ctypes.c_uint8), # unsigned char
52
+ ("minutes_flag", ctypes.c_uint8), # unsigned char
53
+ ("hours_flag", ctypes.c_uint8), # unsigned char
54
+ ("time_offset_length", ctypes.c_uint8), # unsigned char
55
+ ("reserved", ctypes.c_uint8), # unsigned char
56
+ ]
57
+
58
+ def __repr__(self):
59
+ return (
60
+ "TIMECODESET(\n"
61
+ f" time_offset_value={self.time_offset_value},\n"
62
+ f" n_frames={self.n_frames},\n"
63
+ f" clock_timestamp_flag={self.clock_timestamp_flag},\n"
64
+ f" units_field_based_flag={self.units_field_based_flag},\n"
65
+ f" counting_type={self.counting_type},\n"
66
+ f" full_timestamp_flag={self.full_timestamp_flag},\n"
67
+ f" discontinuity_flag={self.discontinuity_flag},\n"
68
+ f" cnt_dropped_flag={self.cnt_dropped_flag},\n"
69
+ f" seconds_value={self.seconds_value},\n"
70
+ f" minutes_value={self.minutes_value},\n"
71
+ f" hours_value={self.hours_value},\n"
72
+ f" seconds_flag={self.seconds_flag},\n"
73
+ f" minutes_flag={self.minutes_flag},\n"
74
+ f" hours_flag={self.hours_flag},\n"
75
+ f" time_offset_length={self.time_offset_length},\n"
76
+ f" reserved={self.reserved}\n"
77
+ ")"
78
+ )
79
+
80
+ class TIMECODE(ctypes.Structure):
81
+ """Structure for time code information."""
82
+ _fields_ = [
83
+ ("time_code_set", TIMECODESET * MAX_CLOCK_TS), # Array of TIMECODESET
84
+ ("num_clock_ts", ctypes.c_uint8), # unsigned char
85
+ ]
86
+
87
+ def __repr__(self):
88
+ time_code_set_repr = ",\n ".join(
89
+ repr(self.time_code_set[i]) for i in range(self.num_clock_ts)
90
+ )
91
+ return (
92
+ "TIMECODE(\n"
93
+ f" time_code_set=[\n {time_code_set_repr}\n ],\n"
94
+ f" num_clock_ts={self.num_clock_ts}\n"
95
+ ")"
96
+ )
97
+
98
+ class SEICONTENTLIGHTLEVELINFO(ctypes.Structure):
99
+ """Structure for content light level information."""
100
+ _fields_ = [
101
+ ("max_content_light_level", ctypes.c_uint16), # unsigned short
102
+ ("max_pic_average_light_level", ctypes.c_uint16), # unsigned short
103
+ ("reserved", ctypes.c_uint32), # unsigned int
104
+ ]
105
+
106
+ def __repr__(self):
107
+ return (
108
+ "SEICONTENTLIGHTLEVELINFO(\n"
109
+ f" max_content_light_level={self.max_content_light_level},\n"
110
+ f" max_pic_average_light_level={self.max_pic_average_light_level},\n"
111
+ f" reserved={self.reserved}\n"
112
+ ")"
113
+ )
114
+
115
+ class SEIMASTERINGDISPLAYINFO(ctypes.Structure):
116
+ """Structure for mastering display information."""
117
+ _fields_ = [
118
+ ("display_primaries_x", ctypes.c_uint16 * 3), # Array of 3 unsigned short
119
+ ("display_primaries_y", ctypes.c_uint16 * 3), # Array of 3 unsigned short
120
+ ("white_point_x", ctypes.c_uint16), # unsigned short
121
+ ("white_point_y", ctypes.c_uint16), # unsigned short
122
+ ("max_display_mastering_luminance", ctypes.c_uint32), # unsigned int
123
+ ("min_display_mastering_luminance", ctypes.c_uint32), # unsigned int
124
+ ]
125
+
126
+ def __repr__(self):
127
+ return (
128
+ "SEIMASTERINGDISPLAYINFO(\n"
129
+ f" display_primaries_x={list(self.display_primaries_x)},\n"
130
+ f" display_primaries_y={list(self.display_primaries_y)},\n"
131
+ f" white_point_x={self.white_point_x},\n"
132
+ f" white_point_y={self.white_point_y},\n"
133
+ f" max_display_mastering_luminance={self.max_display_mastering_luminance},\n"
134
+ f" min_display_mastering_luminance={self.min_display_mastering_luminance}\n"
135
+ ")"
136
+ )
137
+
138
+ class TIMECODEMPEG2(ctypes.Structure):
139
+ """Structure for MPEG2 time code information."""
140
+ _fields_ = [
141
+ ("drop_frame_flag", ctypes.c_uint8), # unsigned char
142
+ ("time_code_hours", ctypes.c_uint8), # unsigned char
143
+ ("time_code_minutes", ctypes.c_uint8), # unsigned char
144
+ ("marker_bit", ctypes.c_uint8), # unsigned char
145
+ ("time_code_seconds", ctypes.c_uint8), # unsigned char
146
+ ("time_code_pictures", ctypes.c_uint8), # unsigned char
147
+ ]
148
+
149
+ def __repr__(self):
150
+ return (
151
+ "TIMECODEMPEG2(\n"
152
+ f" drop_frame_flag={self.drop_frame_flag},\n"
153
+ f" time_code_hours={self.time_code_hours},\n"
154
+ f" time_code_minutes={self.time_code_minutes},\n"
155
+ f" marker_bit={self.marker_bit},\n"
156
+ f" time_code_seconds={self.time_code_seconds},\n"
157
+ f" time_code_pictures={self.time_code_pictures}\n"
158
+ ")"
159
+ )
160
+
161
+ class SEIALTERNATIVETRANSFERCHARACTERISTICS(ctypes.Structure):
162
+ """Structure for alternative transfer characteristics."""
163
+ _fields_ = [
164
+ ("preferred_transfer_characteristics", ctypes.c_uint8), # unsigned char
165
+ ]
166
+
167
+ def __repr__(self):
168
+ return f"SEIALTERNATIVETRANSFERCHARACTERISTICS(preferred_transfer_characteristics={self.preferred_transfer_characteristics})"
169
+
170
+ def write_sei_messages(sei_messages, sei_file_path, script_dir=None):
171
+ """
172
+ Write SEI messages to output files.
173
+
174
+ This function writes SEI messages in three formats:
175
+ 1. sei_message.bin - Raw binary SEI messages
176
+ 2. sei_type_message.bin - Pickled SEI type information
177
+ 3. sei_message.txt - Human-readable parsed SEI content
178
+
179
+ Parameters:
180
+ sei_messages (list): List of tuples containing (sei_info, sei_message)
181
+ sei_file_path (str): Path to output file (base name for all three files)
182
+ script_dir (str, optional): Directory for type message file. If None, uses sei_file_path's directory.
183
+
184
+ Returns:
185
+ None
186
+ """
187
+ # Determine output paths
188
+ if script_dir is None:
189
+ script_dir = dirname(abspath(sei_file_path))
190
+
191
+ sei_type_message_path = join(script_dir, "sei_type_message.bin")
192
+
193
+ # Open files for storing SEI data
194
+ with open(sei_file_path, "wb") as file_message, \
195
+ open(sei_type_message_path, "wb") as file_type_message:
196
+
197
+ for sei_info, sei_message in sei_messages:
198
+ sei_type = sei_info["sei_type"]
199
+ sei_uncompressed = sei_info["sei_uncompressed"]
200
+
201
+ if sei_uncompressed == 1:
202
+ buffer = (ctypes.c_ubyte * len(sei_message))(*sei_message)
203
+ sei_struct = None
204
+
205
+ # Handle different SEI message types
206
+ if sei_type in (nvc.SEI_TYPE.TIME_CODE_H264, nvc.SEI_TYPE.TIME_CODE):
207
+ sei_struct = ctypes.cast(
208
+ buffer,
209
+ ctypes.POINTER(TIMECODEMPEG2 if codec_id == nvc.cudaVideoCodec.MPEG2 else TIMECODE)
210
+ ).contents
211
+ elif sei_type == nvc.SEI_TYPE.MASTERING_DISPLAY_COLOR_VOLUME:
212
+ sei_struct = ctypes.cast(buffer, ctypes.POINTER(SEIMASTERINGDISPLAYINFO)).contents
213
+ elif sei_type == nvc.SEI_TYPE.CONTENT_LIGHT_LEVEL_INFO:
214
+ sei_struct = ctypes.cast(buffer, ctypes.POINTER(SEICONTENTLIGHTLEVELINFO)).contents
215
+ elif sei_type == nvc.SEI_TYPE.ALTERNATIVE_TRANSFER_CHARACTERISTICS:
216
+ sei_struct = ctypes.cast(buffer, ctypes.POINTER(SEIALTERNATIVETRANSFERCHARACTERISTICS)).contents
217
+
218
+ if sei_struct:
219
+ print(sei_struct)
220
+
221
+ file_message.write(bytearray(sei_message))
222
+ pickle.dump(sei_messages, file_type_message)
223
+ print(f"SEI message written to {sei_file_path}")