PyNvVideoCodec 2.0.4__cp314-cp314-win_amd64.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 (65) hide show
  1. PyNvVideoCodec/PyNvVideoCodec_121.cp314-win_amd64.pyd +0 -0
  2. PyNvVideoCodec/PyNvVideoCodec_130.cp314-win_amd64.pyd +0 -0
  3. PyNvVideoCodec/VersionCheck.cp314-win_amd64.pyd +0 -0
  4. PyNvVideoCodec/__init__.py +246 -0
  5. PyNvVideoCodec/avcodec-62.dll +0 -0
  6. PyNvVideoCodec/avdevice-62.dll +0 -0
  7. PyNvVideoCodec/avfilter-11.dll +0 -0
  8. PyNvVideoCodec/avformat-62.dll +0 -0
  9. PyNvVideoCodec/avutil-60.dll +0 -0
  10. PyNvVideoCodec/decoders/SimpleDecoder.py +230 -0
  11. PyNvVideoCodec/decoders/ThreadedDecoder.py +129 -0
  12. PyNvVideoCodec/decoders/__init__.py +22 -0
  13. PyNvVideoCodec/swresample-6.dll +0 -0
  14. PyNvVideoCodec/swscale-9.dll +0 -0
  15. PyNvVideoCodec/transcoder/Transcoder.py +55 -0
  16. PyNvVideoCodec/transcoder/__init__.py +22 -0
  17. benchmarks/cached_decoder_benchmark.py +813 -0
  18. benchmarks/frame_sampling_benchmark.py +765 -0
  19. benchmarks/requirements.txt +47 -0
  20. benchmarks/segmented_transcode_benchmark.py +1546 -0
  21. pynvvideocodec-2.0.4.data/data/external/ffmpeg/readme.txt +15 -0
  22. pynvvideocodec-2.0.4.data/data/external/ffmpeg/src/ffmpeg-8.1.1.tar.xz +0 -0
  23. pynvvideocodec-2.0.4.dist-info/METADATA +84 -0
  24. pynvvideocodec-2.0.4.dist-info/RECORD +65 -0
  25. pynvvideocodec-2.0.4.dist-info/WHEEL +5 -0
  26. pynvvideocodec-2.0.4.dist-info/licenses/LICENSE.txt +22 -0
  27. pynvvideocodec-2.0.4.dist-info/licenses/NOTICES.txt +167 -0
  28. pynvvideocodec-2.0.4.dist-info/top_level.txt +3 -0
  29. samples/advanced/decode.py +173 -0
  30. samples/advanced/decode_from_memory_buffer.py +204 -0
  31. samples/advanced/decode_perf.py +299 -0
  32. samples/advanced/decode_reconfigure.py +184 -0
  33. samples/advanced/decode_sei_msg.py +193 -0
  34. samples/advanced/decode_with_cuda_control.py +214 -0
  35. samples/advanced/decode_with_low_latency.py +183 -0
  36. samples/advanced/encode_config.json +9 -0
  37. samples/advanced/encode_config_lowlatency.json +11 -0
  38. samples/advanced/encode_perf.py +338 -0
  39. samples/advanced/encode_reconfigure.py +211 -0
  40. samples/advanced/encode_sei_msg.py +188 -0
  41. samples/advanced/simple_decode_stats.py +179 -0
  42. samples/advanced/transcode.py +288 -0
  43. samples/basic/create_video_segments.py +187 -0
  44. samples/basic/encode.py +347 -0
  45. samples/basic/encode_config.json +9 -0
  46. samples/basic/segments.txt +3 -0
  47. samples/basic/simple_decode_sampling.py +182 -0
  48. samples/basic/transcode_config.json +6 -0
  49. samples/jupyter/ReconfigureDecoder.png +0 -0
  50. samples/jupyter/SimpleDecoderAPIs.png +0 -0
  51. samples/jupyter/ThreadedDecoder.png +0 -0
  52. samples/jupyter/coco_classes.pickle +0 -0
  53. samples/jupyter/object_detection_tutorial.ipynb +762 -0
  54. samples/jupyter/simple_decode_tutorial.ipynb +651 -0
  55. samples/requirements.txt +78 -0
  56. samples/utils/Utils.py +405 -0
  57. samples/utils/__init__.py +36 -0
  58. samples/utils/decode_parser.py +642 -0
  59. samples/utils/decode_stats_writer.py +177 -0
  60. samples/utils/encode_parallel_utils.py +174 -0
  61. samples/utils/encode_parser.py +357 -0
  62. samples/utils/frame_utils.py +89 -0
  63. samples/utils/sei_message_parser.py +223 -0
  64. samples/utils/sei_parser.py +223 -0
  65. 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
+ -c: Codec (H264, HEVC, AV1)
55
+ -f: Number of frames (default: all)
56
+ -g: GPU ID (default: 0)
57
+ -json: Encoder config file
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,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
+ )
@@ -0,0 +1,288 @@
1
+ # This copyright notice applies to this file only
2
+ #
3
+ # SPDX-FileCopyrightText: Copyright (c) 2025 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
+ Transcode video files using NVIDIA's GPU zero-copy pipeline -- demux ->
26
+ NVDEC -> NVENC -> mux, with audio passthrough.
27
+
28
+ It shows how to:
29
+ 1. Create a runtime CUDA context and stream and pass them to decoder + encoder
30
+ 2. Decode an input video file to GPU memory
31
+ 3. Re-encode the decoded frames in-place (no host round-trip) to a different
32
+ codec / container
33
+ 4. Demux video + audio in lockstep (DemuxNoSkipAudio) and mux both to the
34
+ output container, preserving the source's A/V interleave + bit-exact PTS
35
+
36
+ CLI is provided by samples/utils/transcode_parser.py
37
+ (parse_advanced_transcode_args). Run with `--help` for the flag list.
38
+
39
+ Example:
40
+ # Transcode H264 -> HEVC, mux to MP4 (video + audio in order)
41
+ python transcode.py -i input.mp4 -o output.mp4 -c HEVC
42
+
43
+ # Same, with diagnostic YUV + raw bitstream dump
44
+ python transcode.py -i input.mp4 -o output.mp4 -c HEVC --dump
45
+
46
+ # Override encoder bitrate / preset / etc. via JSON
47
+ python transcode.py -i input.mp4 -o output.mp4 -c H264 -json my_config.json
48
+ """
49
+
50
+ import sys
51
+ from pathlib import Path
52
+ from os.path import dirname, abspath
53
+
54
+ import pycuda.driver as cuda
55
+
56
+ # Add the parent directory to Python path so `utils.*` imports resolve
57
+ current_dir = dirname(abspath(__file__))
58
+ parent_dir = dirname(current_dir)
59
+ if parent_dir not in sys.path:
60
+ sys.path.append(parent_dir)
61
+
62
+ import PyNvVideoCodec as nvc
63
+
64
+ from utils.Utils import get_frame_data, GetChromaFormat, GetVideoCodec
65
+ from utils.transcode_parser import parse_advanced_transcode_args
66
+
67
+
68
+ def transcode(gpu_id, input_path, output_path, encoder_config,
69
+ dump_diagnostics=False):
70
+ """Decode + encode + mux a single video file end-to-end on the GPU.
71
+
72
+ Parameters:
73
+ gpu_id (int): GPU ordinal.
74
+ input_path (str): Path to the input video file (any container or
75
+ elementary bitstream FFmpeg can demux).
76
+ output_path (str): Path to the output video file. A container
77
+ extension (.mp4 / .mov / .mkv / ...) triggers muxing of both
78
+ video and audio.
79
+ encoder_config (dict): Encoder kwargs (codec, preset, bf, fps, ...)
80
+ as produced by load_advanced_transcode_config(). This dict is
81
+ mutated in-place with the GPU/CUDA/source-context handles
82
+ before being splatted into nvc.CreateEncoder.
83
+ dump_diagnostics (bool): If True, dump decoded YUV +
84
+ encoded bitstream to <output_stem>_decoded.yuv /
85
+ <output_stem>_encoded.<ext> for offline inspection.
86
+ """
87
+ print("Using GPU buffer mode for transcoding")
88
+
89
+ cuda_ctx = None
90
+ cuda_stream = None
91
+ nv_dmx = None
92
+ nv_dec = None
93
+ nv_enc = None
94
+ muxer = None
95
+ dec_dump_file = None
96
+ enc_dump_file = None
97
+
98
+ try:
99
+ # CUDA context + stream shared by decoder and encoder.
100
+ cuda.init()
101
+ cuda_device = cuda.Device(gpu_id)
102
+ cuda_ctx = cuda_device.retain_primary_context()
103
+ cuda_ctx.push()
104
+ cuda_stream = cuda.Stream()
105
+ print(f"Created CUDA context and stream for GPU {gpu_id}")
106
+
107
+ # Demuxer + input-stream metadata.
108
+ nv_dmx = nvc.CreateDemuxer(filename=input_path)
109
+ width = nv_dmx.Width()
110
+ height = nv_dmx.Height()
111
+ input_codec = nv_dmx.GetNvCodecId()
112
+ print(f"Input video: {width}x{height} @ {nv_dmx.FrameRate()} FPS "
113
+ f"({nv_dmx.GetContainerName()})")
114
+ print(f"Input codec: {input_codec}")
115
+
116
+ # Codec / preset defaults (only used if JSON / CLI didn't set them).
117
+ encoder_config.setdefault("codec", GetVideoCodec(nv_dmx).lower())
118
+ encoder_config.setdefault("preset", "P4")
119
+
120
+ output_format = GetChromaFormat(nv_dmx)
121
+
122
+ nv_dec = nvc.CreateDecoder(
123
+ gpuid=gpu_id,
124
+ codec=input_codec,
125
+ cudacontext=cuda_ctx.handle,
126
+ cudastream=cuda_stream.handle,
127
+ usedevicememory=1,
128
+ )
129
+
130
+ # Hand the source AVFormatContext to the encoder. This single
131
+ # handle drives three pieces of bit-exactness automatically
132
+ # (see NvEncoderClInterface.cpp):
133
+ # * ExtractSourceFrameRate -> NVENC frameRateNum/Den (VFR)
134
+ # * ExtractSourceColorMeta -> NVENC SPS VUI color signals
135
+ # * HasSourceAVFormatContext -> global_header (container-mode)
136
+ # Callers without a source context (encode.py + raw YUV, matrix
137
+ # tests) skip all three paths and keep their existing elementary-
138
+ # stream defaults.
139
+ encoder_config["gpu_id"] = gpu_id
140
+ encoder_config["cudacontext"] = cuda_ctx.handle
141
+ encoder_config["cudastream"] = cuda_stream.handle
142
+ encoder_config["source_av_format_context"] = int(
143
+ nv_dmx.GetAVFormatInputContext()
144
+ )
145
+
146
+ nv_enc = nvc.CreateEncoder(
147
+ width, height, output_format, False, **encoder_config,
148
+ )
149
+
150
+ print(f"Output codec: {encoder_config['codec']}")
151
+ print(f"Output format: {output_format}")
152
+ print(f"B-frames (encoder): {nv_enc.GetNumBFrames()}")
153
+ print(f"Output timebase: {nv_dmx.GetTimebaseNum()}/"
154
+ f"{nv_dmx.GetTimebaseDen()} (matches input)")
155
+
156
+ # Diagnostic dump files (decoded frames, encoded bitstream).
157
+ if dump_diagnostics:
158
+ enc_stem = Path(output_path).stem
159
+ codec_ext = {"h264": "h264", "hevc": "hevc", "av1": "av1"}.get(
160
+ encoder_config["codec"].lower(), "bin")
161
+ dec_dump_path = Path(output_path).parent / f"{enc_stem}_decoded.yuv"
162
+ enc_dump_path = Path(output_path).parent / f"{enc_stem}_encoded.{codec_ext}"
163
+ dec_dump_file = open(dec_dump_path, "wb")
164
+ enc_dump_file = open(enc_dump_path, "wb")
165
+ print(f"Diagnostic dump: decoded -> {dec_dump_path}, "
166
+ f"encoded -> {enc_dump_path}")
167
+
168
+ muxer = nvc.FFmpegMuxer(
169
+ file_path=output_path,
170
+ media_format=nvc.GetMediaFormat(output_path),
171
+ in_format_context=nv_dmx.GetAVFormatInputContext(),
172
+ codec=encoder_config["codec"].lower(),
173
+ width=width,
174
+ height=height,
175
+ extradata=nv_enc.GetSequenceParams(),
176
+ )
177
+
178
+ # All A/V interleave bookkeeping, B-frame DTS slack, and VFR PTS
179
+ # correction live inside FFmpegMuxer (see RecordSourceVideoPacket /
180
+ # MuxVideoPacket / MuxPassthroughPacket / Finalize). This loop is
181
+ # the canonical "decode -> encode -> mux" reference and stays short
182
+ # enough that a user can copy it into their own app.
183
+ input_frame_idx = 0
184
+ while True:
185
+ pkt = nv_dmx.DemuxNoSkipAudio()
186
+
187
+ if pkt.is_video or pkt.bsl == 0:
188
+ muxer.RecordSourceVideoPacket(pkt)
189
+
190
+ for decoded_frame in nv_dec.Decode(pkt):
191
+ pic_params = nvc.NV_ENC_PIC_PARAMS()
192
+ pic_params.inputTimeStamp = input_frame_idx
193
+ input_frame_idx += 1
194
+
195
+ if dump_diagnostics:
196
+ frame_data = get_frame_data(decoded_frame, use_device_memory=1)
197
+ dec_dump_file.write(bytearray(frame_data))
198
+
199
+ for enc_pkt in nv_enc.Encode(decoded_frame, pic_params):
200
+ if dump_diagnostics:
201
+ enc_dump_file.write(bytes(enc_pkt['data']))
202
+ muxer.MuxVideoPacket(
203
+ bytes(enc_pkt['data']),
204
+ enc_pkt['picture_type'],
205
+ enc_pkt['timestamp'],
206
+ )
207
+
208
+ if pkt.bsl == 0:
209
+ break
210
+ else:
211
+ muxer.MuxPassthroughPacket(pkt)
212
+
213
+ for enc_pkt in nv_enc.EndEncode():
214
+ if dump_diagnostics:
215
+ enc_dump_file.write(bytes(enc_pkt['data']))
216
+ muxer.MuxVideoPacket(
217
+ bytes(enc_pkt['data']),
218
+ enc_pkt['picture_type'],
219
+ enc_pkt['timestamp'],
220
+ )
221
+
222
+ muxer.Finalize()
223
+
224
+ print(f"Output file: {output_path}")
225
+
226
+ except nvc.PyNvVCExceptionUnsupported as e:
227
+ print(f"Unsupported operation: {e}")
228
+ raise
229
+ except cuda.Error as e:
230
+ print(f"CUDA error (context/stream): {e}")
231
+ raise
232
+ except Exception as e:
233
+ print(f"Error during transcoding: {e}")
234
+ raise
235
+ finally:
236
+ # Close diagnostic dump files
237
+ if dec_dump_file is not None:
238
+ dec_dump_file.close()
239
+ if enc_dump_file is not None:
240
+ enc_dump_file.close()
241
+ # Cleanup resources in reverse order of creation
242
+ if muxer is not None:
243
+ del muxer
244
+ if nv_enc is not None:
245
+ del nv_enc
246
+ if nv_dec is not None:
247
+ del nv_dec
248
+ if nv_dmx is not None:
249
+ del nv_dmx
250
+ if cuda_stream is not None:
251
+ cuda_stream.synchronize()
252
+ del cuda_stream
253
+ if cuda_ctx is not None:
254
+ cuda_ctx.pop()
255
+ del cuda_ctx
256
+
257
+
258
+ if __name__ == "__main__":
259
+ args = parse_advanced_transcode_args(
260
+ "Transcode video files using GPU zero-copy pipeline -- convert "
261
+ "from one codec/format to another."
262
+ )
263
+
264
+ print("=" * 60)
265
+ print("TRANSCODER CONFIGURATION")
266
+ print("=" * 60)
267
+ print(f"Input file: {args.input}")
268
+ print(f"Output file: {args.output}")
269
+ print(f"Codec: {args.codec if args.codec else 'from input'}")
270
+ print(f"GPU ID: {args.gpu_id}")
271
+ print(f"FPS override: {args.fps if args.fps else 'auto (from input)'}")
272
+ print(f"Dump diagnostics: {args.dump}")
273
+ print(f"B-frames (CLI): "
274
+ f"{args.bframes if args.bframes is not None else 'config default'}")
275
+ print("Resolution / format: from input")
276
+ print("=" * 60)
277
+
278
+ transcode(
279
+ args.gpu_id,
280
+ args.input.as_posix(),
281
+ args.output.as_posix(),
282
+ args.config,
283
+ dump_diagnostics=args.dump,
284
+ )
285
+
286
+ print("=" * 60)
287
+ print("TRANSCODE COMPLETE")
288
+ print("=" * 60)