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
|
@@ -0,0 +1,288 @@
|
|
|
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
|
+
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)
|
|
@@ -0,0 +1,187 @@
|
|
|
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 video segmentation which can be useful for creating training data for machine learning models.
|
|
26
|
+
It shows how to:
|
|
27
|
+
1. Extract segments from a video file based on timestamp ranges
|
|
28
|
+
2. Use the SimpleDecoder to get video metadata
|
|
29
|
+
3. Configure and use the Transcoder for segment extraction
|
|
30
|
+
4. Handle multiple output segments with proper naming
|
|
31
|
+
|
|
32
|
+
Usage:
|
|
33
|
+
python create_video_segments.py -i <input_file> [options]
|
|
34
|
+
|
|
35
|
+
Example:
|
|
36
|
+
python create_video_segments.py -i input.mp4 -s segments.txt -c config.json
|
|
37
|
+
|
|
38
|
+
Arguments:
|
|
39
|
+
-i: Input video file
|
|
40
|
+
-s: Segments file (default: segments.txt)
|
|
41
|
+
-c: Transcoder config file (default: transcode_config.json)
|
|
42
|
+
-o: Output filename template
|
|
43
|
+
-g: GPU ID (default: 0)
|
|
44
|
+
|
|
45
|
+
Segments File Format:
|
|
46
|
+
start_time end_time
|
|
47
|
+
Example:
|
|
48
|
+
0.0 10.5
|
|
49
|
+
15.0 30.0
|
|
50
|
+
45.5 60.0
|
|
51
|
+
|
|
52
|
+
Output file format:
|
|
53
|
+
This is the default output template. The file name can be customized using the -o argument. Time stamp is appended to the file name.
|
|
54
|
+
{input_file_name}_segment_{start_time}_{end_time}.mp4
|
|
55
|
+
Example:
|
|
56
|
+
input_file_name_segment_0.0_10.5.mp4
|
|
57
|
+
input_file_name_segment_15.0_30.0.mp4
|
|
58
|
+
input_file_name_segment_45.5_60.0.mp4
|
|
59
|
+
|
|
60
|
+
Note: Times are in seconds. Each segment is validated against video duration.
|
|
61
|
+
'''
|
|
62
|
+
|
|
63
|
+
import json
|
|
64
|
+
import os
|
|
65
|
+
import sys
|
|
66
|
+
from os.path import dirname, abspath
|
|
67
|
+
import PyNvVideoCodec as nvc
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
# Add the parent directory to Python path in a way that works from any working directory
|
|
71
|
+
current_dir = dirname(abspath(__file__))
|
|
72
|
+
parent_dir = dirname(current_dir)
|
|
73
|
+
if parent_dir not in sys.path:
|
|
74
|
+
sys.path.append(parent_dir)
|
|
75
|
+
|
|
76
|
+
from utils.transcode_parser import parse_transcode_args
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def get_video_duration(input_file_path: str, gpu_id: int) -> float:
|
|
80
|
+
"""Get video duration in seconds."""
|
|
81
|
+
try:
|
|
82
|
+
decoder = nvc.SimpleDecoder(input_file_path, gpu_id=gpu_id)
|
|
83
|
+
duration = decoder.get_stream_metadata().duration
|
|
84
|
+
print(f"Video duration: {duration:.2f} seconds")
|
|
85
|
+
return duration
|
|
86
|
+
except Exception as e:
|
|
87
|
+
print(f"Error getting video duration: {e}")
|
|
88
|
+
return 0.0
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def create_video_segments(input_file_path: str, segments_file_path: str,
|
|
92
|
+
config_file_path: str, output_template: str, gpu_id: int):
|
|
93
|
+
"""Create video segments from input file based on segments text file."""
|
|
94
|
+
|
|
95
|
+
# Get video duration for validation
|
|
96
|
+
duration = get_video_duration(input_file_path, gpu_id)
|
|
97
|
+
if duration <= 0:
|
|
98
|
+
print("Error: Could not determine video duration")
|
|
99
|
+
return
|
|
100
|
+
|
|
101
|
+
# Load transcoder configuration
|
|
102
|
+
with open(config_file_path) as json_file:
|
|
103
|
+
config = json.load(json_file)
|
|
104
|
+
|
|
105
|
+
input_file_name_base = os.path.splitext(os.path.basename(input_file_path))[0]
|
|
106
|
+
successful_segments = 0
|
|
107
|
+
|
|
108
|
+
# Process segments file
|
|
109
|
+
with open(segments_file_path, 'r') as file:
|
|
110
|
+
for line_num, line in enumerate(file, 1):
|
|
111
|
+
line = line.strip()
|
|
112
|
+
if not line: # Skip empty lines
|
|
113
|
+
continue
|
|
114
|
+
|
|
115
|
+
try:
|
|
116
|
+
start_ts_str, end_ts_str = line.split()
|
|
117
|
+
start_time = float(start_ts_str)
|
|
118
|
+
end_time = float(end_ts_str)
|
|
119
|
+
|
|
120
|
+
# Error check: end timestamp should not exceed media duration
|
|
121
|
+
if end_time > duration:
|
|
122
|
+
print(f"Warning: Line {line_num}: End time {end_time:.2f}s exceeds video duration {duration:.2f}s - clipping to duration")
|
|
123
|
+
end_time = duration
|
|
124
|
+
|
|
125
|
+
if start_time >= end_time:
|
|
126
|
+
print(f"Error: Line {line_num}: Invalid time range {start_time}-{end_time}")
|
|
127
|
+
continue
|
|
128
|
+
|
|
129
|
+
# Generate output path
|
|
130
|
+
base_output_path = output_template.format(input_file_name=input_file_name_base)
|
|
131
|
+
base_output_name, base_output_ext = os.path.splitext(base_output_path)
|
|
132
|
+
if not base_output_ext:
|
|
133
|
+
base_output_ext = '.mp4'
|
|
134
|
+
base_output_path = base_output_name + base_output_ext
|
|
135
|
+
|
|
136
|
+
start_time = round(start_time, 2)
|
|
137
|
+
end_time = round(end_time, 2)
|
|
138
|
+
print(f"Creating segment: {start_time:g}s - {end_time:g}s")
|
|
139
|
+
|
|
140
|
+
# Create transcoder and generate segment
|
|
141
|
+
transcoder = nvc.Transcoder(input_file_path, base_output_path, gpu_id, 0, 0, **config)
|
|
142
|
+
transcoder.segmented_transcode(start_time, end_time)
|
|
143
|
+
|
|
144
|
+
# Expected output filename (API appends timestamps)
|
|
145
|
+
final_output = f"{base_output_name}_{start_time:g}_{end_time:g}{base_output_ext}"
|
|
146
|
+
print(f"✓ Created: {final_output}")
|
|
147
|
+
successful_segments += 1
|
|
148
|
+
|
|
149
|
+
except ValueError as e:
|
|
150
|
+
print(f"Error: Line {line_num}: Invalid format '{line}' - {e}")
|
|
151
|
+
except Exception as e:
|
|
152
|
+
print(f"Error: Line {line_num}: Failed to create segment - {e}")
|
|
153
|
+
|
|
154
|
+
print(f"\nSummary: {successful_segments} segments created successfully")
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def main():
|
|
158
|
+
args = parse_transcode_args("Create video segments from text file input")
|
|
159
|
+
|
|
160
|
+
# Display configuration
|
|
161
|
+
print("=" * 60)
|
|
162
|
+
print("VIDEO SEGMENTATION CONFIGURATION")
|
|
163
|
+
print("=" * 60)
|
|
164
|
+
print(f"Input: {args.input_file_path}")
|
|
165
|
+
print(f"Segments File: {args.segments_file_path}")
|
|
166
|
+
print(f"Config File: {args.config_file_path}")
|
|
167
|
+
print(f"GPU ID: {args.gpu_id}")
|
|
168
|
+
print("=" * 60)
|
|
169
|
+
|
|
170
|
+
# Validate files exist
|
|
171
|
+
for file_path, name in [(args.input_file_path, "Input video"),
|
|
172
|
+
(args.segments_file_path, "Segments file"),
|
|
173
|
+
(args.config_file_path, "Config file")]:
|
|
174
|
+
if not os.path.exists(file_path):
|
|
175
|
+
print(f"Error: {name} not found: {file_path}")
|
|
176
|
+
return
|
|
177
|
+
|
|
178
|
+
create_video_segments(args.input_file_path, args.segments_file_path, args.config_file_path,
|
|
179
|
+
args.output_template, args.gpu_id)
|
|
180
|
+
|
|
181
|
+
print("=" * 60)
|
|
182
|
+
print("SEGMENTATION COMPLETE")
|
|
183
|
+
print("=" * 60)
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
if __name__ == "__main__":
|
|
187
|
+
main()
|