forked from jianchang512/pyvideotrans
-
Notifications
You must be signed in to change notification settings - Fork 0
/
testcuda.py
579 lines (524 loc) · 27.4 KB
/
testcuda.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
# 测试 CUDA 可用性
# 找到一个 h264 编码的mp4视频,重命名为 raw.mp4,然后复制到和当前脚本同目录下,然后执行测试
import json
import subprocess
import torch
import os
import sys
from torch.backends import cudnn
# ffmpeg
rootdir = os.getcwd()
tmpdir = os.path.join(rootdir, 'tmp')
if sys.platform == 'win32':
os.environ['PATH'] = rootdir + f';{rootdir}\\ffmpeg;' + os.environ['PATH']
else:
os.environ['PATH'] = rootdir + f':{rootdir}/ffmpeg:' + os.environ['PATH']
if torch.cuda.is_available():
print('CUDA is ok')
else:
print("no CUDA environ")
input("\nPress enter for close")
sys.exit()
if cudnn.is_available() and cudnn.is_acceptable(torch.tensor(1.).cuda()):
print('cudnn is ok')
else:
print('no cudnn ')
input("\nPress enter for close")
sys.exit()
result = subprocess.run(['ffmpeg', '-hwaccels'], text=True, stdout=subprocess.PIPE)
print(f'Accels:\n{result.stdout}')
if not os.path.exists(tmpdir):
os.makedirs(tmpdir, exist_ok=True)
# 原始视频
sourcemp4 = rootdir + "/raw.mp4"
sourceavi = rootdir + "/raw.mp4.avi"
if not os.path.exists(sourcemp4):
print('\ncopy a video rename raw.mp4, and paster to here')
input("\nPress enter for close")
sys.exit()
def runffmpeg(cmd, *, title=""):
p = subprocess.Popen(cmd,
stdout=subprocess.PIPE,
encoding="utf-8",
stderr=subprocess.PIPE)
outs, errs = p.communicate()
if p.returncode == 0:
print(f'\n[OK] {title}:\n{cmd=}\n')
return True
print("\n\n******Its Error*******")
print(f'\n[Error] {title}\n')
print(f'{cmd=}')
print(str(errs))
print("\n******Error*******\n")
for (i, it) in enumerate(cmd):
if it == '-hwaccel' and cmd[i] == 'cuda':
print(f'hwaccel_output_format=cuda Dont Support, But hwaccel_output_format=nv12 is OK')
break
input("\nPress enter for close")
sys.exit()
def runffprobe(cmd):
try:
p = subprocess.run(['ffprobe'] + cmd, stdout=subprocess.PIPE, text=True)
if p.returncode == 0:
return p.stdout.strip()
else:
print(f'{p.stderr=}')
return False
except subprocess.CalledProcessError as e:
print(f'{e=}')
return False
# 获取视频信息
def get_video_info(mp4_file, *, video_fps=False, video_scale=False, video_time=False):
out = runffprobe(['-v', 'quiet', '-print_format', 'json', '-show_format', '-show_streams', mp4_file])
if out is False:
raise Exception(f'ffprobe error:dont get video information')
out = json.loads(out)
result = {
"video_fps": 0,
"video_codec_name": "h264",
"audio_codec_name": "aac",
"width": 0,
"height": 0,
"time": 0,
"streams_len": 0,
"streams_audio": 0
}
if "streams" not in out or len(out["streams"]) < 1:
raise Exception(f'ffprobe error:streams is 0')
if "format" in out and out['format']['duration']:
result['time'] = int(float(out['format']['duration']) * 1000)
for it in out['streams']:
result['streams_len'] += 1
if it['codec_type'] == 'video':
result['video_codec_name'] = it['codec_name']
result['width'] = int(it['width'])
result['height'] = int(it['height'])
fps, c = it['r_frame_rate'].split('/')
if not c or c == '0':
c = 1
fps = int(fps)
else:
fps = round(int(fps) / int(c))
result['video_fps'] = fps
elif it['codec_type'] == 'audio':
result['streams_audio'] += 1
result['audio_codec_name'] = it['codec_name']
if video_time:
return result['time']
if video_fps:
return ['video_fps']
if video_scale:
return result['width'], result['height']
return result
def test_cuda(*, hwaccel_output_format=""):
if hwaccel_output_format == "cuda":
acc_name = "cuda"
libx264 = "h264_nvenc"
elif hwaccel_output_format == 'nv12':
acc_name = "cuvid"
libx264 = "h264_nvenc"
else:
acc_name = None
libx264 = "libx264"
# 从视频中截取的图片
img = os.path.join(tmpdir, '1.jpg')
# 从原始视频中分离出的无声视频
novoice = os.path.join(tmpdir, 'novoice.mp4')
# 视频 音频 硬字幕合并后输出
out_hard = os.path.join(tmpdir, 'out_hard.mp4')
# 视频 音频 软字幕合并后输出
out_soft = os.path.join(tmpdir, 'out_soft.mp4')
# 配音无字幕
out_nosrt = os.path.join(tmpdir, 'out_nosrt.mp4')
# 从原始视频中分离出音频
m4a = os.path.join(tmpdir, '1.m4a')
# m4a 格式转为 wav格式
wav = os.path.join(tmpdir, '1.wav')
wavspeedup = os.path.join(tmpdir, '1-speedup.wav')
# 连接2个视频片段
concat = os.path.join(tmpdir, 'concat.txt')
# 字幕文件
srtfile = os.path.join(tmpdir, 'zimu.srt')
# 根据图片生成的视频
imgvideo = os.path.join(tmpdir, 'img.mp4')
# 从视频中截取的片段
pianduan = os.path.join(tmpdir, 'pianduan.mp4')
# 图片视频片段和截取的片段合并
hebing = os.path.join(tmpdir, 'imgvideo-pianduan.mp4')
# 获取视频信息
video_info = get_video_info(sourcemp4)
if not video_info or video_info['time'] == 0:
print("The video is error,please replace")
input("\nPress enter will close")
sys.exit()
print(f"start test -hwaccel_output_format={hwaccel_output_format} ...")
if video_info['video_codec_name'] != 'h264' or video_info['audio_codec_name'] != 'aac':
# 转换
tmptestmp4 = os.path.join(rootdir, 'tmptest.mp4')
accel_pre = ["ffmpeg", "-hide_banner", '-ignore_unknown'] if not acc_name else ['ffmpeg',
'-hide_banner',
'-ignore_unknown',
'-vsync',
'vfr',
'-hwaccel',
acc_name,
'-hwaccel_output_format',
hwaccel_output_format,
'-extra_hw_frames',
'2']
runffmpeg(accel_pre + [
'-y',
'-i',
sourcemp4,
'-c:v',
libx264,
'-c:a',
'aac',
tmptestmp4]
, title="raw.mp4格式不正确,请确保是h264编码的mp4视频")
os.unlink(sourcemp4)
os.rename(tmptestmp4, sourcemp4)
# 获取视频信息
video_info = get_video_info(sourcemp4)
if not video_info or video_info['time'] == 0:
print("The video is error,please replace")
input("\nPress enter will close")
sys.exit()
fps = video_info['video_fps']
scale = [video_info['width'], video_info['height']]
# 从原始视频 分离出无声视频 cuda + h264_cuvid
accel_pre = ["ffmpeg", "-hide_banner", '-ignore_unknown'] if not acc_name else ['ffmpeg',
'-hide_banner',
'-ignore_unknown',
'-vsync',
'vfr',
'-hwaccel',
acc_name,
'-hwaccel_output_format',
hwaccel_output_format,
'-extra_hw_frames',
'2', '-c:v',
'h264_cuvid', ]
runffmpeg(accel_pre + [
'-y',
'-i',
sourcemp4,
'-an',
'-c:v',
libx264,
novoice]
, title='从原始视频 分离出无声视频')
# 从原始视频 分离出音频 cuda + h264_cuvid
accel_pre = ["ffmpeg", "-hide_banner", '-ignore_unknown'] if not acc_name else ['ffmpeg',
'-hide_banner',
'-ignore_unknown',
'-vsync',
'vfr',
'-hwaccel',
acc_name,
'-hwaccel_output_format',
hwaccel_output_format,
'-extra_hw_frames',
'2', '-c:v',
'h264_cuvid', ]
runffmpeg(accel_pre + [
'-y',
'-i',
sourcemp4,
'-vn',
'-c:a',
'copy',
m4a]
, title='从原始视频 分离出音频')
# 分离出的 m4a 转为 wav cuda + h264_cuvid
accel_pre = ["ffmpeg", "-hide_banner", '-ignore_unknown'] if not acc_name else ['ffmpeg',
'-hide_banner',
'-ignore_unknown',
'-vsync',
'vfr',
'-hwaccel',
acc_name,
'-hwaccel_output_format',
hwaccel_output_format,
'-extra_hw_frames',
'2', '-c:v',
'h264_cuvid', ]
runffmpeg(accel_pre + [
'-y',
'-i',
m4a,
'-ac',
'1',
wav]
, title='分离出的 m4a 转为 wav')
# 提取最后一帧为图片 nv12 + h264_cuvid
accel_pre = ["ffmpeg", "-hide_banner", '-ignore_unknown'] if not acc_name else ['ffmpeg',
'-hide_banner',
'-ignore_unknown',
'-vsync',
'vfr',
'-hwaccel',
acc_name,
'-hwaccel_output_format',
"nv12",
'-extra_hw_frames',
'2', '-c:v',
'h264_cuvid', ]
runffmpeg(accel_pre + [
'-y',
'-sseof',
'-3',
'-i',
novoice,
'-q:v',
'1',
'-qmin:v',
'1',
'-qmax:v',
'1',
'-update',
'true',
img]
, title='提取最后一帧为图片')
# 根据图片创建 5s 的视频 nv12 + not h264_cuvid
accel_pre = ["ffmpeg", "-hide_banner", '-ignore_unknown'] if not acc_name else ['ffmpeg',
'-hide_banner',
'-ignore_unknown',
'-vsync',
'vfr',
'-hwaccel',
acc_name,
'-hwaccel_output_format',
"nv12",
'-extra_hw_frames',
'2', ]
runffmpeg(accel_pre + [
'-y',
'-loop',
'1',
'-i',
img,
'-vf',
f"fps={fps},scale={scale[0]}:{scale[1]}",
'-c:v',
libx264,
'-crf',
'13',
'-to',
'00:00:05',
imgvideo]
, title='根据图片创建 5s 的视频')
# 截取 00:00:05 -- 00:00:15 nv12 + not h264_cuvid
accel_pre = ["ffmpeg", "-hide_banner", '-ignore_unknown'] if not acc_name else ['ffmpeg',
'-hide_banner',
'-ignore_unknown',
'-vsync',
'vfr',
'-hwaccel',
acc_name,
'-hwaccel_output_format',
hwaccel_output_format,
'-extra_hw_frames',
'2', '-c:v',
'h264_cuvid', ]
runffmpeg(accel_pre + [
'-y',
'-ss',
'00:00:05',
'-to',
'00:00:10.500',
'-i',
novoice,
'-vf',
"setpts=2*PTS",
'-c:v',
libx264,
'-crf',
'13',
pianduan]
, title='截取 00:00:05 -- 00:00:15')
# imgvideo 和 pianduan 合并
srttext = f"""
file '{imgvideo}'
file '{pianduan}'
"""
with open(concat, 'w', encoding='utf-8') as f:
f.write(srttext)
# 连接 2个视频片段 cuda + h264_cuvid
accel_pre = ["ffmpeg", "-hide_banner", '-ignore_unknown'] if not acc_name else ['ffmpeg',
'-hide_banner',
'-ignore_unknown',
'-vsync',
'vfr',
'-hwaccel',
acc_name,
'-hwaccel_output_format',
hwaccel_output_format,
'-extra_hw_frames',
'2', '-c:v',
'h264_cuvid', ]
runffmpeg(accel_pre + [
'-y',
'-f',
'concat',
'-safe',
'0',
'-i',
concat,
'-c:v',
libx264,
'-crf',
'13',
'-an',
hebing]
, title='连接 2个视频片段')
with open(srtfile, 'w', encoding='utf-8') as f:
f.write("""
1
00:00:00,000 --> 00:00:05,780
rear seat
2
00:00:05,780 --> 00:00:08,436
In this issue we introduce electromagnetic punishment in the park
3
00:00:08,436 --> 00:00:10,132
First of all, we got an electromagnetic penalty""")
if sys.platform == 'win32':
hardfile = os.path.basename(srtfile)
else:
hardfile = srtfile
# 视频 音频 硬字幕合并 nv12 + h264_cuvid
os.chdir(os.path.dirname(srtfile))
accel_pre = ["ffmpeg", "-hide_banner", '-ignore_unknown'] if not acc_name else ['ffmpeg',
'-hide_banner',
'-ignore_unknown',
'-vsync',
'vfr',
'-hwaccel',
acc_name,
'-hwaccel_output_format',
"nv12",
'-extra_hw_frames',
'2', '-c:v',
'h264_cuvid', ]
runffmpeg(accel_pre + [
'-y',
'-i',
novoice,
'-i',
m4a,
'-c:v',
libx264,
'-c:a',
'copy',
'-vf',
f'subtitles={hardfile}',
out_hard]
, title='视频 音频 硬字幕合并')
# 视频 硬字幕 nv12 + h264_cuvid
accel_pre = ["ffmpeg", "-hide_banner", '-ignore_unknown'] if not acc_name else ['ffmpeg',
'-hide_banner',
'-ignore_unknown',
'-vsync',
'vfr',
'-hwaccel',
acc_name,
'-hwaccel_output_format',
"nv12",
'-extra_hw_frames',
'2', '-c:v',
'h264_cuvid', ]
runffmpeg(accel_pre + [
'-y',
'-i',
novoice,
'-c:v',
libx264,
'-vf',
f'subtitles={hardfile}',
out_hard]
, title='视频 硬字幕')
# 视频 配音 软字幕 cuda + h264_cuvid
accel_pre = ["ffmpeg", "-hide_banner", '-ignore_unknown'] if not acc_name else ['ffmpeg',
'-hide_banner',
'-ignore_unknown',
'-vsync',
'vfr',
'-hwaccel',
acc_name,
'-hwaccel_output_format',
hwaccel_output_format,
'-extra_hw_frames',
'2', '-c:v',
'h264_cuvid', ]
runffmpeg(accel_pre + [
'-y',
'-i',
novoice,
'-i',
m4a,
'-i',
srtfile,
'-c:v',
libx264,
'-c:a',
'copy',
'-c:s',
'mov_text',
'-metadata:s:s:0',
'language=chi',
out_soft]
, title='视频 配音 软字幕')
# 软字幕无配音 cuda + h264_cuvid
accel_pre = ["ffmpeg", "-hide_banner", '-ignore_unknown'] if not acc_name else ["ffmpeg", "-hide_banner",
"-ignore_unknown", "-vsync", "vfr",
"-hwaccel", acc_name,
"-hwaccel_output_format",
hwaccel_output_format,
"-extra_hw_frames", "2", "-c:v",
"h264_cuvid", ]
runffmpeg(
accel_pre + ["-y", "-i", novoice, "-i", srtfile, "-c:v", libx264, "-c:s", "mov_text",
"-metadata:s:s:0", "language=chi", out_soft], title='软字幕无配音')
# 配音无字幕
accel_pre = ["ffmpeg", "-hide_banner", '-ignore_unknown'] if not acc_name else ["ffmpeg", "-hide_banner",
"-ignore_unknown", "-vsync", "vfr",
"-hwaccel", acc_name,
"-hwaccel_output_format",
hwaccel_output_format,
"-extra_hw_frames", "2", "-c:v",
"h264_cuvid", ]
runffmpeg(accel_pre + ["-y", "-i", novoice, "-i", m4a, "-c:v", libx264, "-c:a", "copy",
out_nosrt], title='配音无字幕')
# 加速音频
accel_pre = ["ffmpeg", "-hide_banner", '-ignore_unknown'] if not acc_name else ["ffmpeg", "-hide_banner",
"-ignore_unknown", "-vsync", "vfr",
"-hwaccel", acc_name,
"-hwaccel_output_format",
hwaccel_output_format,
"-extra_hw_frames", "2", "-c:v",
"h264_cuvid", ]
runffmpeg(accel_pre + ["-y", "-i", wav, "-af", "atempo=2", wavspeedup], title='加速音频')
# mp4 转为 api
accel_pre = ["ffmpeg", "-hide_banner", '-ignore_unknown'] if not acc_name else ["ffmpeg", "-hide_banner",
"-ignore_unknown", "-vsync", "vfr",
"-hwaccel", acc_name,
"-hwaccel_output_format", "nv12",
"-extra_hw_frames", "2", ]
runffmpeg(accel_pre + ["-y", "-i", sourcemp4, "-c:v", libx264, "-c:a", "aac", sourceavi], title='mp4 转为 avi')
# avi 转为 mp4
accel_pre = ["ffmpeg", "-hide_banner", '-ignore_unknown'] if not acc_name else ["ffmpeg", "-hide_banner",
"-ignore_unknown", "-vsync", "vfr",
"-hwaccel", acc_name,
"-hwaccel_output_format",
hwaccel_output_format,
"-extra_hw_frames", "2", ]
runffmpeg(accel_pre + ["-y", "-i", sourceavi, "-c:v", libx264, "-c:a", "aac", f"{sourceavi}.mp4"],
title='avi 转为 mp4')
test_cuda(hwaccel_output_format="nv12")
print("\n[hwaccel_output_format=nv12 is ok,CUDA OK】\n\n")
print("\nNext will test hwaccel_output_format=cuda\n")
test_cuda(hwaccel_output_format="cuda")
print(
"hwaccel_output_format=cuda is ok\nMay be open videotrans/set.ini\nedit 'hwaccel_output_format=nv12' to 'hwaccel_output_format=cuda'\n And edit 'hwaccel=cuvid' to 'hwaccel=cuda'")
input("\nPress enter for close")