PyNvVideoCodec 2.2.1__cp314-cp314-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.
- PyNvVideoCodec/PyNvVideoCodec_121.cp314-win_arm64.pyd +0 -0
- PyNvVideoCodec/PyNvVideoCodec_130.cp314-win_arm64.pyd +0 -0
- PyNvVideoCodec/VersionCheck.cp314-win_arm64.pyd +0 -0
- PyNvVideoCodec/__init__.py +251 -0
- PyNvVideoCodec/avformat-62.dll +0 -0
- PyNvVideoCodec/avutil-60.dll +0 -0
- PyNvVideoCodec/decoders/SimpleDecoder.py +273 -0
- PyNvVideoCodec/decoders/ThreadedDecoder.py +129 -0
- PyNvVideoCodec/decoders/__init__.py +22 -0
- PyNvVideoCodec/transcoder/Transcoder.py +55 -0
- PyNvVideoCodec/transcoder/__init__.py +22 -0
- benchmarks/cached_decoder_benchmark.py +813 -0
- benchmarks/frame_sampling_benchmark.py +765 -0
- benchmarks/requirements.txt +52 -0
- benchmarks/segmented_transcode_benchmark.py +1546 -0
- benchmarks/setup_pycuda_win_arm64.bat +531 -0
- pynvvideocodec-2.2.1.data/data/external/ffmpeg/readme.txt +39 -0
- pynvvideocodec-2.2.1.data/data/external/ffmpeg/src/ffmpeg-8.1.2.tar.xz +0 -0
- pynvvideocodec-2.2.1.dist-info/METADATA +97 -0
- pynvvideocodec-2.2.1.dist-info/RECORD +63 -0
- pynvvideocodec-2.2.1.dist-info/WHEEL +5 -0
- pynvvideocodec-2.2.1.dist-info/licenses/LICENSE.txt +22 -0
- pynvvideocodec-2.2.1.dist-info/licenses/NOTICES.txt +167 -0
- pynvvideocodec-2.2.1.dist-info/top_level.txt +3 -0
- samples/advanced/decode.py +173 -0
- samples/advanced/decode_from_memory_buffer.py +204 -0
- samples/advanced/decode_perf.py +299 -0
- samples/advanced/decode_reconfigure.py +184 -0
- samples/advanced/decode_sei_msg.py +193 -0
- samples/advanced/decode_with_cuda_control.py +214 -0
- samples/advanced/decode_with_low_latency.py +183 -0
- samples/advanced/encode_config.json +12 -0
- samples/advanced/encode_config_lowlatency.json +13 -0
- samples/advanced/encode_perf.py +338 -0
- samples/advanced/encode_reconfigure.py +211 -0
- samples/advanced/encode_sei_msg.py +188 -0
- samples/advanced/simple_decode_from_memory.py +151 -0
- samples/advanced/simple_decode_stats.py +179 -0
- samples/advanced/transcode.py +288 -0
- samples/basic/create_video_segments.py +187 -0
- samples/basic/encode.py +574 -0
- samples/basic/segments.txt +3 -0
- samples/basic/simple_decode_sampling.py +182 -0
- samples/basic/transcode_config.json +6 -0
- samples/jupyter/ReconfigureDecoder.png +0 -0
- samples/jupyter/SimpleDecoderAPIs.png +0 -0
- samples/jupyter/ThreadedDecoder.png +0 -0
- samples/jupyter/coco_classes.pickle +0 -0
- samples/jupyter/face_protect_tutorial.ipynb +881 -0
- samples/jupyter/object_detection_tutorial.ipynb +781 -0
- samples/jupyter/simple_decode_tutorial.ipynb +674 -0
- samples/requirements.txt +84 -0
- samples/setup_pycuda_win_arm64.bat +531 -0
- samples/utils/Utils.py +405 -0
- samples/utils/__init__.py +36 -0
- samples/utils/decode_parser.py +642 -0
- samples/utils/decode_stats_writer.py +177 -0
- samples/utils/encode_parallel_utils.py +174 -0
- samples/utils/encode_parser.py +379 -0
- samples/utils/frame_utils.py +89 -0
- samples/utils/sei_message_parser.py +223 -0
- samples/utils/sei_parser.py +223 -0
- samples/utils/transcode_parser.py +218 -0
samples/basic/encode.py
ADDED
|
@@ -0,0 +1,574 @@
|
|
|
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 unified video encoding with support for both CPU and GPU buffer modes,
|
|
26
|
+
with optional muxing to container formats (MP4, MOV, WEBM).
|
|
27
|
+
|
|
28
|
+
It shows how to:
|
|
29
|
+
1. Configure and use different buffer modes for encoding
|
|
30
|
+
2. Handle both host (CPU) and device (GPU) memory efficiently
|
|
31
|
+
3. Manage encoder resources and states
|
|
32
|
+
4. Process frames with optimal memory handling
|
|
33
|
+
5. Mux encoded streams into container formats
|
|
34
|
+
|
|
35
|
+
The sample supports two buffer modes:
|
|
36
|
+
- CPU Buffer Mode:
|
|
37
|
+
* Uses host memory for frame data
|
|
38
|
+
|
|
39
|
+
- GPU Buffer Mode:
|
|
40
|
+
* Uses device memory for frame data
|
|
41
|
+
|
|
42
|
+
Usage:
|
|
43
|
+
python encode.py -i <input_file> -s <size> -m <mode> [options]
|
|
44
|
+
|
|
45
|
+
Note:
|
|
46
|
+
FPS and GOP size are configured via the JSON config file (see -json).
|
|
47
|
+
Codec can be set via -c on the CLI (takes priority) or via the JSON config.
|
|
48
|
+
The default JSON config sets codec=h264, fps=30, gop=30.
|
|
49
|
+
|
|
50
|
+
Examples:
|
|
51
|
+
# Encode to MP4 container (auto-mux from .mp4 extension)
|
|
52
|
+
python encode.py -i input.yuv -s 1920x1080 -m gpu -o output.mp4
|
|
53
|
+
|
|
54
|
+
# Encode to raw H.264 bitstream (auto: .h264 extension = no muxing)
|
|
55
|
+
python encode.py -i input.yuv -s 1920x1080 -m gpu -o output.h264
|
|
56
|
+
|
|
57
|
+
# AV1 elementary (.av1): IVF container + patched frame count (AppEncCuda-compatible); use MP4 output for container muxing.
|
|
58
|
+
# Set "codec": "av1" in the JSON config file before running.
|
|
59
|
+
python encode.py -i input.yuv -s 1920x1080 -m cpu -json my_av1_config.json -o output.av1
|
|
60
|
+
|
|
61
|
+
Arguments:
|
|
62
|
+
-i: Raw input video file
|
|
63
|
+
-s: Frame size (e.g., 1920x1080)
|
|
64
|
+
-m: Buffer mode (cpu/gpu)
|
|
65
|
+
-if: Input format (default: NV12)
|
|
66
|
+
-f: Number of frames (default: all)
|
|
67
|
+
-g: GPU ID (default: 0)
|
|
68
|
+
-c: Output codec (h264/hevc/av1); overrides codec in JSON config
|
|
69
|
+
-json: Encoder config file (controls codec, fps, gop, preset, rc, bitrate, etc.)
|
|
70
|
+
-o: Output file (use a container extension like .mp4 or .mov to enable muxing)
|
|
71
|
+
'''
|
|
72
|
+
|
|
73
|
+
import PyNvVideoCodec as nvc
|
|
74
|
+
import numpy as np
|
|
75
|
+
import json
|
|
76
|
+
import argparse
|
|
77
|
+
from pathlib import Path
|
|
78
|
+
import os
|
|
79
|
+
import sys
|
|
80
|
+
from os.path import join, dirname, abspath
|
|
81
|
+
|
|
82
|
+
# Add the parent directory to Python path in a way that works from any working directory
|
|
83
|
+
current_dir = dirname(abspath(__file__))
|
|
84
|
+
parent_dir = dirname(current_dir)
|
|
85
|
+
if parent_dir not in sys.path:
|
|
86
|
+
sys.path.append(parent_dir)
|
|
87
|
+
|
|
88
|
+
# Import utilities for GPU buffer mode
|
|
89
|
+
try:
|
|
90
|
+
from utils.Utils import AppFrame, FetchCPUFrame, FetchGPUFrame
|
|
91
|
+
GPU_UTILS_AVAILABLE = True
|
|
92
|
+
except ImportError:
|
|
93
|
+
GPU_UTILS_AVAILABLE = False
|
|
94
|
+
print("Warning: Utils module not found. GPU buffer mode will be disabled.")
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
# Import utilities for frame handling
|
|
98
|
+
from utils.frame_utils import get_frame_size
|
|
99
|
+
from utils.encode_parser import parse_unified_args
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
# Container formats that support muxing
|
|
105
|
+
CONTAINER_FORMATS = {'.mp4', '.mov', '.mkv', '.webm', '.avi'}
|
|
106
|
+
|
|
107
|
+
# Supported codec+container combinations for muxing.
|
|
108
|
+
# Keys are extensions, values are the set of codecs that work in that container.
|
|
109
|
+
_SUPPORTED_MUX = {
|
|
110
|
+
'.mp4': {'h264', 'hevc', 'av1'},
|
|
111
|
+
'.mov': {'h264', 'hevc'},
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
# Standard MPEG timebase (90 kHz) used for muxed output.
|
|
115
|
+
_TIMEBASE = 90000
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def should_mux(output_path: str) -> bool:
|
|
119
|
+
"""Check if output file extension indicates a container format."""
|
|
120
|
+
ext = Path(output_path).suffix.lower()
|
|
121
|
+
return ext in CONTAINER_FORMATS
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def validate_mux_support(codec: str, output_path: str) -> None:
|
|
125
|
+
"""
|
|
126
|
+
Raise ValueError if the codec+container combination is not supported.
|
|
127
|
+
|
|
128
|
+
Supported combinations:
|
|
129
|
+
MP4: H264, HEVC, AV1
|
|
130
|
+
MOV: H264, HEVC
|
|
131
|
+
"""
|
|
132
|
+
ext = Path(output_path).suffix.lower()
|
|
133
|
+
supported_codecs = _SUPPORTED_MUX.get(ext)
|
|
134
|
+
if supported_codecs is None:
|
|
135
|
+
supported = ', '.join(sorted(f'*{e}' for e in _SUPPORTED_MUX))
|
|
136
|
+
raise ValueError(
|
|
137
|
+
f"Muxing to '{ext}' is not supported. Supported containers: {supported}"
|
|
138
|
+
)
|
|
139
|
+
if codec.lower() not in supported_codecs:
|
|
140
|
+
raise ValueError(
|
|
141
|
+
f"Muxing {codec.upper()} into '{ext}' is not supported. "
|
|
142
|
+
f"Supported codecs for {ext}: {', '.join(sorted(c.upper() for c in supported_codecs))}"
|
|
143
|
+
)
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def get_media_format(output_path: str):
|
|
147
|
+
"""
|
|
148
|
+
Get media format enum from file extension.
|
|
149
|
+
|
|
150
|
+
Uses PyNvVideoCodec's built-in GetMediaFormat function to get the
|
|
151
|
+
proper MEDIA_FORMAT enum value required by FFmpegMuxer.
|
|
152
|
+
|
|
153
|
+
Args:
|
|
154
|
+
output_path: Path to output file
|
|
155
|
+
|
|
156
|
+
Returns:
|
|
157
|
+
MEDIA_FORMAT enum value (e.g., nvc.MEDIA_FORMAT.MP4)
|
|
158
|
+
"""
|
|
159
|
+
return nvc.GetMediaFormat(output_path)
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def _concat_encode_packets(packets) -> bytes:
|
|
163
|
+
"""Join Encode / EndEncode output into one bitstream blob."""
|
|
164
|
+
return b"".join(bytes(p["data"]) for p in packets)
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def _av1_ivf_elementary_enabled(config_params: dict, use_muxer: bool) -> bool:
|
|
169
|
+
"""True when output is AV1 in IVF (elementary), matching VideoCodecSDK AppEncCuda."""
|
|
170
|
+
if use_muxer or config_params.get("codec", "h264").lower() != "av1":
|
|
171
|
+
return False
|
|
172
|
+
v = str(config_params.get("use_ivf_container", "1")).lower()
|
|
173
|
+
return v not in ("0", "false", "no")
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def _patch_ivf_output_file(output_file_path: str, ivf_packet_count: int) -> None:
|
|
177
|
+
"""Match FFmpeg ivf_write_trailer: frame count at IVF global header offset 24 (LE32)."""
|
|
178
|
+
if ivf_packet_count <= 0:
|
|
179
|
+
return
|
|
180
|
+
with open(output_file_path, "r+b") as out_f:
|
|
181
|
+
if out_f.read(4) != b"DKIF":
|
|
182
|
+
return
|
|
183
|
+
out_f.seek(24)
|
|
184
|
+
out_f.write(ivf_packet_count.to_bytes(4, "little"))
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def get_extradata_from_encoder(encoder) -> bytes:
|
|
188
|
+
"""
|
|
189
|
+
Get sequence parameters (SPS/PPS/VPS) from encoder.
|
|
190
|
+
|
|
191
|
+
This uses the NVENC API's GetSequenceParams function to retrieve the
|
|
192
|
+
codec-specific header data required by container formats.
|
|
193
|
+
|
|
194
|
+
Args:
|
|
195
|
+
encoder: The PyNvEncoder instance
|
|
196
|
+
|
|
197
|
+
Returns:
|
|
198
|
+
bytes: Sequence parameter data for muxer extradata
|
|
199
|
+
"""
|
|
200
|
+
return encoder.GetSequenceParams()
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def encode_cpu_buffer(gpu_id, dec_file_path, enc_file_path, width, height, fmt, config_params, frame_count, gop_size, fps, use_mux=None):
|
|
204
|
+
"""
|
|
205
|
+
Encode frames using host memory buffers as input.
|
|
206
|
+
|
|
207
|
+
This function reads image data from a file and copies it to CUDA buffers for encoding.
|
|
208
|
+
The encoder submits the data to NVENC hardware for encoding. Video memory buffer is
|
|
209
|
+
allocated to get the NVENC hardware output. The output is copied from video memory
|
|
210
|
+
to host memory for file storage.
|
|
211
|
+
|
|
212
|
+
Parameters:
|
|
213
|
+
gpu_id (int): Ordinal of GPU to use
|
|
214
|
+
dec_file_path (str): Path to file to be decoded
|
|
215
|
+
enc_file_path (str): Path to output file for encoded frames
|
|
216
|
+
width (int): Width of encoded frame
|
|
217
|
+
height (int): Height of encoded frame
|
|
218
|
+
fmt (str): Surface format string in uppercase (e.g., "NV12")
|
|
219
|
+
config_params (dict): Key-value pairs providing fine-grained control on encoding
|
|
220
|
+
frame_count (int): Number of frames to encode
|
|
221
|
+
gop_size (int): GOP size (keyframe interval)
|
|
222
|
+
fps (int): Frame rate (frames per second) for muxing
|
|
223
|
+
use_mux (bool): If True, mux to container. If False, raw bitstream. If None, auto-detect.
|
|
224
|
+
|
|
225
|
+
Returns:
|
|
226
|
+
None
|
|
227
|
+
"""
|
|
228
|
+
print("Using CPU buffer mode")
|
|
229
|
+
|
|
230
|
+
# Check if we need to mux (use override if provided, otherwise auto-detect)
|
|
231
|
+
use_muxer = use_mux if use_mux is not None else should_mux(enc_file_path)
|
|
232
|
+
codec = config_params.get("codec", "h264").lower()
|
|
233
|
+
if codec == "av1":
|
|
234
|
+
if use_muxer:
|
|
235
|
+
config_params["use_ivf_container"] = "0"
|
|
236
|
+
else:
|
|
237
|
+
config_params.setdefault("use_ivf_container", "1")
|
|
238
|
+
|
|
239
|
+
frame_size = get_frame_size(width, height, fmt)
|
|
240
|
+
|
|
241
|
+
if use_muxer:
|
|
242
|
+
validate_mux_support(codec, enc_file_path)
|
|
243
|
+
print(f"Will mux output to container format: {Path(enc_file_path).suffix}")
|
|
244
|
+
|
|
245
|
+
with open(dec_file_path, "rb") as dec_file:
|
|
246
|
+
config_params["gpu_id"] = gpu_id
|
|
247
|
+
nvenc = nvc.CreateEncoder(width, height, fmt, True, **config_params) # True = use CPU buffers
|
|
248
|
+
|
|
249
|
+
# Calculate total available frames from file size
|
|
250
|
+
file_size = os.path.getsize(dec_file_path)
|
|
251
|
+
available_frames = file_size // frame_size
|
|
252
|
+
|
|
253
|
+
# Determine frames to process with limit
|
|
254
|
+
frames_to_process = frame_count if frame_count > 0 else available_frames
|
|
255
|
+
frames_to_process = min(frames_to_process, available_frames)
|
|
256
|
+
|
|
257
|
+
print(f"File contains {available_frames} frames, processing {frames_to_process} frames using CPU buffers...")
|
|
258
|
+
|
|
259
|
+
# Muxing parameters
|
|
260
|
+
pts_increment = _TIMEBASE // fps
|
|
261
|
+
|
|
262
|
+
# Initialize muxer or output file
|
|
263
|
+
muxer = None
|
|
264
|
+
enc_file = None
|
|
265
|
+
|
|
266
|
+
if use_muxer:
|
|
267
|
+
# Get sequence parameters (SPS/PPS) from encoder for muxer extradata
|
|
268
|
+
extradata = get_extradata_from_encoder(nvenc)
|
|
269
|
+
print(f"Extracted extradata size: {len(extradata)} bytes")
|
|
270
|
+
|
|
271
|
+
media_format = get_media_format(enc_file_path)
|
|
272
|
+
muxer = nvc.FFmpegMuxer(
|
|
273
|
+
file_path=enc_file_path,
|
|
274
|
+
media_format=media_format,
|
|
275
|
+
codec=codec,
|
|
276
|
+
width=width,
|
|
277
|
+
height=height,
|
|
278
|
+
fps_num=fps,
|
|
279
|
+
fps_den=1,
|
|
280
|
+
timebase_num=1,
|
|
281
|
+
timebase_den=_TIMEBASE,
|
|
282
|
+
extradata=extradata
|
|
283
|
+
)
|
|
284
|
+
# Inform the muxer of the uniform frame duration so Finalize()
|
|
285
|
+
# generates correct PTS/DTS without needing source container PTS.
|
|
286
|
+
muxer.SetUniformPtsIncrement(pts_increment)
|
|
287
|
+
else:
|
|
288
|
+
# Open raw output file
|
|
289
|
+
enc_file = open(enc_file_path, "wb")
|
|
290
|
+
|
|
291
|
+
frames_encoded = 0
|
|
292
|
+
ivf_packets = 0
|
|
293
|
+
|
|
294
|
+
for i in range(frames_to_process):
|
|
295
|
+
chunk = np.fromfile(dec_file, np.uint8, count=frame_size)
|
|
296
|
+
if chunk.size != 0:
|
|
297
|
+
pic_params = nvc.NV_ENC_PIC_PARAMS()
|
|
298
|
+
pic_params.inputTimeStamp = frames_encoded
|
|
299
|
+
enc_list = nvenc.Encode(chunk, pic_params)
|
|
300
|
+
ivf_packets += len(enc_list)
|
|
301
|
+
|
|
302
|
+
if use_muxer:
|
|
303
|
+
for enc_packet in enc_list:
|
|
304
|
+
muxer.MuxVideoPacket(bytes(enc_packet["data"]),
|
|
305
|
+
enc_packet["picture_type"],
|
|
306
|
+
enc_packet["timestamp"])
|
|
307
|
+
else:
|
|
308
|
+
enc_file.write(bytearray(_concat_encode_packets(enc_list)))
|
|
309
|
+
|
|
310
|
+
frames_encoded += 1
|
|
311
|
+
else:
|
|
312
|
+
print(f"Warning: Could not read frame {i+1}")
|
|
313
|
+
break
|
|
314
|
+
|
|
315
|
+
flush_list = nvenc.EndEncode()
|
|
316
|
+
ivf_packets += len(flush_list)
|
|
317
|
+
if use_muxer:
|
|
318
|
+
for flush_packet in flush_list:
|
|
319
|
+
muxer.MuxVideoPacket(bytes(flush_packet["data"]),
|
|
320
|
+
flush_packet["picture_type"],
|
|
321
|
+
flush_packet["timestamp"])
|
|
322
|
+
muxer.Finalize()
|
|
323
|
+
else:
|
|
324
|
+
bitstream = _concat_encode_packets(flush_list)
|
|
325
|
+
enc_file.write(bytearray(bitstream))
|
|
326
|
+
if _av1_ivf_elementary_enabled(config_params, use_muxer):
|
|
327
|
+
enc_file.flush()
|
|
328
|
+
_patch_ivf_output_file(enc_file_path, ivf_packets)
|
|
329
|
+
enc_file.close()
|
|
330
|
+
|
|
331
|
+
print(f"Completed encoding {frames_encoded} frames using CPU buffers")
|
|
332
|
+
print(f"Output file: {enc_file_path}")
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
def encode_gpu_buffer(gpu_id, dec_file_path, enc_file_path, width, height, fmt, config_params, frame_count, gop_size, fps, use_mux=None):
|
|
336
|
+
"""
|
|
337
|
+
Encode frames using CUDA device buffers as input.
|
|
338
|
+
|
|
339
|
+
This function reads image data from a file and loads it to CUDA input buffers using
|
|
340
|
+
FetchGPUFrame(). The encoder copies the CUDA buffers and submits them to NVENC hardware
|
|
341
|
+
for encoding. Video memory buffer is allocated to get the NVENC hardware output.
|
|
342
|
+
The output is copied from video memory to host memory for file storage.
|
|
343
|
+
|
|
344
|
+
Parameters:
|
|
345
|
+
gpu_id (int): Ordinal of GPU to use
|
|
346
|
+
dec_file_path (str): Path to file to be decoded
|
|
347
|
+
enc_file_path (str): Path to output file for encoded frames
|
|
348
|
+
width (int): Width of encoded frame
|
|
349
|
+
height (int): Height of encoded frame
|
|
350
|
+
fmt (str): Surface format string in uppercase (e.g., "NV12")
|
|
351
|
+
config_params (dict): Key-value pairs providing fine-grained control on encoding
|
|
352
|
+
frame_count (int): Number of frames to encode
|
|
353
|
+
gop_size (int): GOP size (keyframe interval)
|
|
354
|
+
fps (int): Frame rate (frames per second) for muxing
|
|
355
|
+
use_mux (bool): If True, mux to container. If False, raw bitstream. If None, auto-detect.
|
|
356
|
+
|
|
357
|
+
Returns:
|
|
358
|
+
None
|
|
359
|
+
"""
|
|
360
|
+
print("Using GPU buffer mode")
|
|
361
|
+
|
|
362
|
+
if not GPU_UTILS_AVAILABLE:
|
|
363
|
+
raise RuntimeError("GPU buffer mode requires Utils module (AppFrame, FetchCPUFrame, FetchGPUFrame)")
|
|
364
|
+
|
|
365
|
+
# Check if we need to mux (use override if provided, otherwise auto-detect)
|
|
366
|
+
use_muxer = use_mux if use_mux is not None else should_mux(enc_file_path)
|
|
367
|
+
codec = config_params.get("codec", "h264").lower()
|
|
368
|
+
if codec == "av1":
|
|
369
|
+
if use_muxer:
|
|
370
|
+
config_params["use_ivf_container"] = "0"
|
|
371
|
+
else:
|
|
372
|
+
config_params.setdefault("use_ivf_container", "1")
|
|
373
|
+
|
|
374
|
+
if use_muxer:
|
|
375
|
+
validate_mux_support(codec, enc_file_path)
|
|
376
|
+
print(f"Will mux output to container format: {Path(enc_file_path).suffix}")
|
|
377
|
+
|
|
378
|
+
# Show encoder capabilities
|
|
379
|
+
caps = nvc.GetEncoderCaps(codec=config_params.get("codec", "h264"))
|
|
380
|
+
if "num_encoder_engines" in caps:
|
|
381
|
+
print(f"Number of NVENCs: {caps['num_encoder_engines']}")
|
|
382
|
+
|
|
383
|
+
with open(dec_file_path, "rb") as decFile:
|
|
384
|
+
config_params["gpu_id"] = gpu_id
|
|
385
|
+
nvenc = nvc.CreateEncoder(width, height, fmt, False, **config_params) # False = use GPU buffers
|
|
386
|
+
input_frame_list = [AppFrame(width, height, fmt) for _ in range(1, 5)]
|
|
387
|
+
|
|
388
|
+
# Calculate total available frames from file size
|
|
389
|
+
file_size = os.path.getsize(dec_file_path)
|
|
390
|
+
available_frames = file_size // input_frame_list[0].frameSize
|
|
391
|
+
|
|
392
|
+
# Determine frames to process with limit
|
|
393
|
+
frames_to_process = frame_count if frame_count > 0 else available_frames
|
|
394
|
+
frames_to_process = min(frames_to_process, available_frames)
|
|
395
|
+
|
|
396
|
+
print(f"File contains {available_frames} frames, processing {frames_to_process} frames using GPU buffers...")
|
|
397
|
+
|
|
398
|
+
# Muxing parameters
|
|
399
|
+
pts_increment = _TIMEBASE // fps
|
|
400
|
+
|
|
401
|
+
# Initialize muxer or output file
|
|
402
|
+
muxer = None
|
|
403
|
+
encFile = None
|
|
404
|
+
|
|
405
|
+
if use_muxer:
|
|
406
|
+
# Get sequence parameters (SPS/PPS) from encoder for muxer extradata
|
|
407
|
+
extradata = get_extradata_from_encoder(nvenc)
|
|
408
|
+
print(f"Extracted extradata size: {len(extradata)} bytes")
|
|
409
|
+
|
|
410
|
+
media_format = get_media_format(enc_file_path)
|
|
411
|
+
muxer = nvc.FFmpegMuxer(
|
|
412
|
+
file_path=enc_file_path,
|
|
413
|
+
media_format=media_format,
|
|
414
|
+
codec=codec,
|
|
415
|
+
width=width,
|
|
416
|
+
height=height,
|
|
417
|
+
fps_num=fps,
|
|
418
|
+
fps_den=1,
|
|
419
|
+
timebase_num=1,
|
|
420
|
+
timebase_den=_TIMEBASE,
|
|
421
|
+
extradata=extradata
|
|
422
|
+
)
|
|
423
|
+
# Inform the muxer of the uniform frame duration so Finalize()
|
|
424
|
+
# generates correct PTS/DTS without needing source container PTS.
|
|
425
|
+
muxer.SetUniformPtsIncrement(pts_increment)
|
|
426
|
+
else:
|
|
427
|
+
# Open raw output file
|
|
428
|
+
encFile = open(enc_file_path, "wb")
|
|
429
|
+
|
|
430
|
+
frames_encoded = 0
|
|
431
|
+
ivf_packets = 0
|
|
432
|
+
|
|
433
|
+
for input_gpu_frame in FetchGPUFrame(
|
|
434
|
+
input_frame_list,
|
|
435
|
+
FetchCPUFrame(decFile, input_frame_list[0].frameSize),
|
|
436
|
+
frames_to_process
|
|
437
|
+
):
|
|
438
|
+
pic_params = nvc.NV_ENC_PIC_PARAMS()
|
|
439
|
+
pic_params.inputTimeStamp = frames_encoded
|
|
440
|
+
enc_list = nvenc.Encode(input_gpu_frame, pic_params)
|
|
441
|
+
ivf_packets += len(enc_list)
|
|
442
|
+
|
|
443
|
+
if use_muxer:
|
|
444
|
+
for enc_packet in enc_list:
|
|
445
|
+
muxer.MuxVideoPacket(bytes(enc_packet["data"]),
|
|
446
|
+
enc_packet["picture_type"],
|
|
447
|
+
enc_packet["timestamp"])
|
|
448
|
+
else:
|
|
449
|
+
encFile.write(bytearray(_concat_encode_packets(enc_list)))
|
|
450
|
+
|
|
451
|
+
frames_encoded += 1
|
|
452
|
+
|
|
453
|
+
flush_list = nvenc.EndEncode()
|
|
454
|
+
ivf_packets += len(flush_list)
|
|
455
|
+
if use_muxer:
|
|
456
|
+
for flush_packet in flush_list:
|
|
457
|
+
muxer.MuxVideoPacket(bytes(flush_packet["data"]),
|
|
458
|
+
flush_packet["picture_type"],
|
|
459
|
+
flush_packet["timestamp"])
|
|
460
|
+
muxer.Finalize()
|
|
461
|
+
else:
|
|
462
|
+
bitstream = bytearray(_concat_encode_packets(flush_list))
|
|
463
|
+
encFile.write(bitstream)
|
|
464
|
+
if _av1_ivf_elementary_enabled(config_params, use_muxer):
|
|
465
|
+
encFile.flush()
|
|
466
|
+
_patch_ivf_output_file(enc_file_path, ivf_packets)
|
|
467
|
+
encFile.close()
|
|
468
|
+
|
|
469
|
+
print(f"Completed encoding {frames_to_process} frames using GPU buffers")
|
|
470
|
+
print(f"Output file: {enc_file_path}")
|
|
471
|
+
|
|
472
|
+
|
|
473
|
+
def encode_unified(gpu_id, dec_file_path, enc_file_path, width, height, fmt, config_params, frame_count, buffer_mode, gop_size, fps, use_mux=None):
|
|
474
|
+
"""
|
|
475
|
+
Unified encoding function that supports both CPU and GPU buffer modes.
|
|
476
|
+
|
|
477
|
+
Parameters:
|
|
478
|
+
gpu_id (int): Ordinal of GPU to use
|
|
479
|
+
dec_file_path (str): Path to file to be decoded
|
|
480
|
+
enc_file_path (str): Path to output file for encoded frames
|
|
481
|
+
width (int): Width of encoded frame
|
|
482
|
+
height (int): Height of encoded frame
|
|
483
|
+
fmt (str): Surface format string in uppercase (e.g., "NV12")
|
|
484
|
+
config_params (dict): Key-value pairs providing fine-grained control on encoding
|
|
485
|
+
frame_count (int): Number of frames to encode
|
|
486
|
+
buffer_mode (str): Buffer mode - "cpu" or "gpu"
|
|
487
|
+
gop_size (int): GOP size (keyframe interval)
|
|
488
|
+
fps (int): Frame rate (frames per second) for muxing
|
|
489
|
+
use_mux (bool): If True, mux to container. If False, raw bitstream. If None, auto-detect.
|
|
490
|
+
|
|
491
|
+
Returns:
|
|
492
|
+
None
|
|
493
|
+
"""
|
|
494
|
+
try:
|
|
495
|
+
if buffer_mode.lower() == "cpu":
|
|
496
|
+
encode_cpu_buffer(gpu_id, dec_file_path, enc_file_path, width, height, fmt, config_params, frame_count, gop_size, fps, use_mux)
|
|
497
|
+
elif buffer_mode.lower() == "gpu":
|
|
498
|
+
encode_gpu_buffer(gpu_id, dec_file_path, enc_file_path, width, height, fmt, config_params, frame_count, gop_size, fps, use_mux)
|
|
499
|
+
else:
|
|
500
|
+
raise ValueError(f"Invalid buffer mode: {buffer_mode}. Must be 'cpu' or 'gpu'")
|
|
501
|
+
|
|
502
|
+
except nvc.PyNvVCExceptionUnsupported as e:
|
|
503
|
+
print(f"CreateEncoder failure: {e}")
|
|
504
|
+
except ValueError as e:
|
|
505
|
+
print(f"Error: {e}")
|
|
506
|
+
sys.exit(1)
|
|
507
|
+
except Exception as e:
|
|
508
|
+
print(f"An unexpected error occurred: {e}")
|
|
509
|
+
|
|
510
|
+
|
|
511
|
+
def validate_gpu_mode(args) -> None:
|
|
512
|
+
"""Validate GPU buffer mode requirements."""
|
|
513
|
+
if args.buffer_mode == "gpu" and not GPU_UTILS_AVAILABLE:
|
|
514
|
+
print("Error: GPU buffer mode requires Utils module, but it's not available.")
|
|
515
|
+
print("Please use CPU buffer mode (-m cpu) or ensure Utils module is accessible.")
|
|
516
|
+
sys.exit(1)
|
|
517
|
+
|
|
518
|
+
|
|
519
|
+
if __name__ == "__main__":
|
|
520
|
+
args = parse_unified_args(
|
|
521
|
+
"Unified encoding application supporting both CPU and GPU buffer modes with optional muxing."
|
|
522
|
+
)
|
|
523
|
+
|
|
524
|
+
# GOP size and FPS are sourced from the JSON config (via load_config)
|
|
525
|
+
gop_size = args.gop_size
|
|
526
|
+
fps = args.fps
|
|
527
|
+
|
|
528
|
+
use_mux = should_mux(str(args.encoded_file_path))
|
|
529
|
+
|
|
530
|
+
# Display configuration
|
|
531
|
+
print("=" * 60)
|
|
532
|
+
print("ENCODER CONFIGURATION")
|
|
533
|
+
print("=" * 60)
|
|
534
|
+
print(f"Buffer mode: {args.buffer_mode.upper()}")
|
|
535
|
+
print(f"Input file: {args.raw_file_path}")
|
|
536
|
+
print(f"Output file: {args.encoded_file_path}")
|
|
537
|
+
print(f"Resolution: {args.width}x{args.height}")
|
|
538
|
+
print(f"Format: {args.format}")
|
|
539
|
+
print(f"Codec: {args.codec}")
|
|
540
|
+
print(f"GPU ID: {args.gpu_id}")
|
|
541
|
+
print(f"GOP size: {gop_size}")
|
|
542
|
+
print(f"Frame rate: {fps} fps")
|
|
543
|
+
print(f"Frame count: {args.frame_count if args.frame_count > 0 else 'All frames'}")
|
|
544
|
+
|
|
545
|
+
# Show muxing status
|
|
546
|
+
if use_mux:
|
|
547
|
+
print(f"Muxing: Enabled ({Path(args.encoded_file_path).suffix.upper()})")
|
|
548
|
+
else:
|
|
549
|
+
print(f"Muxing: Disabled (raw bitstream)")
|
|
550
|
+
|
|
551
|
+
print("=" * 60)
|
|
552
|
+
|
|
553
|
+
# Validate GPU mode requirements
|
|
554
|
+
validate_gpu_mode(args)
|
|
555
|
+
|
|
556
|
+
# Run encoding
|
|
557
|
+
encode_unified(
|
|
558
|
+
args.gpu_id,
|
|
559
|
+
args.raw_file_path.as_posix(),
|
|
560
|
+
args.encoded_file_path.as_posix(),
|
|
561
|
+
args.width,
|
|
562
|
+
args.height,
|
|
563
|
+
args.format,
|
|
564
|
+
args.config,
|
|
565
|
+
args.frame_count,
|
|
566
|
+
args.buffer_mode,
|
|
567
|
+
gop_size,
|
|
568
|
+
fps,
|
|
569
|
+
use_mux
|
|
570
|
+
)
|
|
571
|
+
|
|
572
|
+
print("=" * 60)
|
|
573
|
+
print("ENCODING COMPLETE")
|
|
574
|
+
print("=" * 60)
|