-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvideo_helper.py
428 lines (383 loc) · 13.1 KB
/
video_helper.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
import json
import os
import random
import re
from datetime import datetime
import subprocess
import asyncio
imagemagick_path = "C:\Program Files\ImageMagick-7.1.1-Q16-HDRI\magick.exe"
stroke_color = "yellow"
stroke_width = 1.2
kerning = 1
width = 1280
height = 720
animation_speed = 1.2
if imagemagick_path:
os.environ["IMAGEMAGICK_BINARY"] = rf"{imagemagick_path}"
async def generate_video(
image_path: str,
name: str,
video_dir_path: str,
audio_dir_path: str,
audio_file_paths: list[str] = None,
srt_file_paths: list[str] = None,
):
"""Generate video by merging all video related materials (incl. pictures, audio files) to a video.
Args:
picture_dir_path (str): path of the directory that contains all pictures
name (str): the novel name
video_dir_path (str): path of the directory for the output video
audio_dir_path (str): path of the directory that contains all audio files
audio_file_paths (list[str]): list of audio files, Default None
srt_file_paths (list[str]): list of srt files, Default None
"""
def extract_number(filename):
match = re.search(r"(\d+)", filename)
if match:
return int(match.group(0))
return 0 # 如果文件名中没有数字,则默认为 0
# picture_path_list = sorted(
# [
# os.path.join(picture_dir_path, name)
# for name in os.listdir(picture_dir_path)
# if name.endswith(".png")
# ],
# key=lambda x: extract_number(os.path.basename(x)),
# )
audio_file_paths = (
sorted(
[
os.path.join(audio_dir_path, name)
for name in os.listdir(audio_dir_path)
if name.endswith(".mp3")
],
key=lambda x: extract_number(os.path.basename(x)),
)
if audio_file_paths is None
else audio_file_paths
)
srt_file_paths = (
sorted(
[
os.path.join(audio_dir_path, name)
for name in os.listdir(audio_dir_path)
if name.endswith(".srt")
],
key=lambda x: extract_number(os.path.basename(x)),
)
if srt_file_paths is None
else srt_file_paths
)
video_list_file_path = os.path.join(video_dir_path, f"{name}.txt")
output_video_path = os.path.join(video_dir_path, f"{name}.mp4")
if os.path.isfile(video_list_file_path):
os.remove(video_list_file_path)
# if os.path.exists(video_dir_path):
# filelist = os.listdir(video_dir_path)
# if len(filelist) != 0: # 开始删除所有文件
# for file in filelist:
# os.remove(os.path.join(video_dir_path, file))
# os.rmdir(video_dir_path)
for index, audio_file_path in enumerate(audio_file_paths, start=1):
video_path = os.path.join(video_dir_path, f"{index}.mp4")
if os.path.exists(video_path):
print(f"{index}.mp4 exists, skip.")
continue
duration = await get_media_length(audio_file_path)
print(f"duration: {duration}")
os.makedirs(video_dir_path, exist_ok=True)
# r"E:\mjpics\剪映图片-大道至簡\%05d.png"
_create_animated_segment(
image_path,
audio_file_path,
duration,
animation_speed,
_get_random_action(),
video_path,
)
# clip.write_videofile(video_path, fps=24, audio_codec="aac")
_add_caption(video_path, srt_file_paths[index - 1])
# update video list
with open(video_list_file_path, "a", encoding="utf-8") as f:
f.write(f"file '{video_path}'\n")
print(f"-----------生成第{index}段视频-----------")
print("-----------开始合成视频-----------")
_concat_videos(video_list_file_path, output_video_path)
# include bgm
print("-----------整合bgm-----------")
# await _add_bgm(output_video_path, "bgm//3.mp3")
# $获取媒体文件长度
async def get_media_length(file_path):
result = subprocess.run(
[
"ffprobe",
"-v",
"error",
"-show_entries",
"format=duration",
"-of",
"default=noprint_wrappers=1:nokey=1",
file_path,
],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
)
return float(result.stdout)
# 获取音频文件的详细信息(比特率、采样率、声道数)
async def get_audio_details(file_path):
cmd = [
"ffprobe",
"-v",
"error",
"-select_streams",
"a:0",
"-show_entries",
"stream=bit_rate,sample_rate,channels",
"-of",
"json",
file_path,
]
result = subprocess.run(cmd, capture_output=True, text=True)
metadata = json.loads(result.stdout)
details = {
"bit_rate": int(metadata["streams"][0]["bit_rate"]),
"sample_rate": int(metadata["streams"][0]["sample_rate"]),
"channels": int(metadata["streams"][0]["channels"]),
}
return details
# 循环BGM以匹配主音轨长度,然后与主音轨混合
async def _add_bgm(video_file, bgm_file):
print("start merging bgm into video ...")
# await merge_bgm("bgm")
main_db = "15"
bgm_db = "0"
video_dir = os.path.dirname(video_file)
tmp_video_file = os.path.join(video_dir, "tmp_bgm.mp4")
converted_bgm = os.path.join(video_dir, "bgm_converted.mp3")
main_length = await get_media_length(video_file)
bgm_length = await get_media_length(bgm_file)
main_volume = f"{main_db}dB"
bgm_volume = f"{bgm_db}dB"
# 计算BGM需要循环的次数
loop_count = int(main_length // bgm_length) + 1 if bgm_length < main_length else 1
# 如果需要,循环BGM
if loop_count > 1:
with open("looped_bgm_list.txt", "w", encoding="utf-8") as loop_file:
for _ in range(loop_count):
loop_file.write(f"file '{bgm_file}'\n")
subprocess.run(
[
"ffmpeg",
"-y",
"-f",
"concat",
"-safe",
"0",
"-i",
"looped_bgm_list.txt",
"-c",
"copy",
"looped_bgm.mp3",
],
check=True,
)
looped_bgm = "looped_bgm.mp3"
os.remove("looped_bgm_list.txt")
else:
looped_bgm = bgm_file
audio_details = await get_audio_details(video_file)
# 采样率、声道和比特率
sample_rate = str(audio_details["sample_rate"])
channels = str(audio_details["channels"])
# bitrate = str(audio_details["bit_rate"])
# 转换循环后的BGM为单声道,采样率调整为24kHz
subprocess.run(
[
"ffmpeg",
"-y",
"-i",
looped_bgm,
"-ac",
str(channels),
"-ar",
str(sample_rate),
converted_bgm,
],
check=True,
)
subprocess.run(
[
"ffmpeg",
"-i",
video_file,
"-i",
converted_bgm,
"-filter_complex",
f"[0:a]volume={main_volume}[a0];[1:a]volume={bgm_volume}[a1];[a0][a1]amerge=inputs=2[a]",
"-map",
"0:v",
"-map",
"[a]",
"-c:v",
"copy",
"-c:a",
"aac",
"-ac",
"2",
tmp_video_file,
],
check=True,
)
# 清理临时文件
# os.remove(converted_bgm)
if loop_count > 1:
os.remove("looped_bgm.mp3")
os.replace(tmp_video_file, video_file)
def _get_random_action():
actions = ["shrink", "left_move", "right_move", "up_move", "down_move"]
return random.choice(actions)
def _create_animated_segment(
image_path, audio_path, duration, multiple, action, output_file
):
initial_zoom = 1.0
zoom_steps = (multiple - initial_zoom) / (25 * duration)
l_r_move = (width * multiple - width - 25) / (25 * duration)
u_d_move = (height * multiple - height - 25 - 25) / (25 * duration)
if action == "shrink":
scale = (
f"scale=-2:ih*10,zoompan=z='if(lte(zoom,{initial_zoom}),{multiple},max(zoom-{zoom_steps},1))':x='iw/2-(iw/zoom/2)':y='ih/2-(ih/zoom/2)':d=25*"
+ str(duration)
+ f":s={width}x{height}"
)
elif action == "left_move":
scale = (
f"scale=-2:ih*10,zoompan='{multiple}':x='if(lte(on,-1),(iw-iw/zoom)/2,x+{l_r_move * 10})':y='if(lte(on,1),(ih-ih/zoom)/2,y)':d=25*"
+ str(duration)
+ f":s={width}x{height}"
)
elif action == "right_move":
scale = (
f"scale=-2:ih*10,zoompan='{multiple}':x='if(lte(on,1),(iw/zoom)/2,x-{l_r_move * 10})':y='if(lte(on,1),(ih-ih/zoom)/2,y)':d=25*"
+ str(duration)
+ f":s={width}x{height}"
)
elif action == "up_move":
scale = (
f"scale=-2:ih*10,zoompan='{multiple}':x='if(lte(on,1),(iw-iw/zoom)/2,x)':y='if(lte(on,-1),(ih-ih/zoom)/2,y+{u_d_move * 10})':d=25*"
+ str(duration)
+ f":s={width}x{height}"
)
elif action == "down_move":
scale = (
f"scale=-2:ih*10,zoompan='{multiple}':x='if(lte(on,1),(iw-iw/zoom)/2,x)':y='if(lte(on,1),(ih/zoom)/2,y-{u_d_move * 10})':d=25*"
+ str(duration)
+ f":s={width}x{height}"
)
else:
scale = f"scale=-2:ih*10,zoompan=z='min(zoom+{zoom_steps},{multiple})*if(gte(zoom,1),1,0)+if(lt(zoom,1),1,0)':x='iw/2-(iw/zoom/2)':y='ih/2-(ih/zoom/2)':d=25*{duration}:s={width}x{height}"
# scale = f"hwupload_cuda,{scale}"
scale = f"format=nv12,hwupload_cuda,scale_cuda=1080:-1"
# Constructing the FFmpeg command
cmd = [
"ffmpeg",
"-framerate",
"0.25", # Every image shows up for 4s
"-y",
"-loop",
"1",
"-t",
str(duration),
"-i",
image_path,
"-i",
audio_path,
"-filter_complex",
scale,
"-c:v",
"h264_nvenc",
"-preset",
"p1",
"-cq",
"30", # Use constant quality
"-c:a",
"aac",
"-b:a",
"192k",
"-r", # output framerate
"30",
output_file,
]
# ffmpeg -loop 1 -i background.jpg -i audio.mp3 -vf "subtitles=subtitle.srt" -c:v h264_nvenc -preset fast -c:a aac -b:a 192k -shortest output.mp4
try:
subprocess.run(cmd, check=True)
except subprocess.CalledProcessError as e:
print(f"Error occurred: {e}")
def _concat_videos(video_list_file_path: str, out_path: str):
subprocess.run(
[
"ffmpeg",
"-f",
"concat",
"-safe",
"0",
"-i",
f"{video_list_file_path}",
"-c",
"copy",
f"{out_path}",
]
)
def _add_caption(video_path, srt_path):
"""Add captions to the video file.
Args:
video_path (str): the original video file (w/o caption)
srt_path (str): the caption file path
"""
fontsize = 20
fontcolor = "FFFFFF"
fontfile = "simhei.ttf"
position = "Alignment=2,MarginV=50"
out_path = os.path.join(os.path.dirname(video_path), "tmp.mp4")
# 构建字体样式字符串,只包含颜色和大小
style = f"FontName={fontfile.split('.')[0]},Fontsize={fontsize},PrimaryColour=&H{fontcolor},Bold=1,{position}"
# 构建 FFmpeg 命令,不再设置字体文件路径
if os.name == "nt":
# 由于绝对路径下win会报错 所以转换成相对路径
proj_path = os.path.abspath("./")
out_path = os.path.relpath(out_path, proj_path).replace("\\", "/")
video_path = os.path.relpath(video_path, proj_path).replace("\\", "/")
srt_path = os.path.relpath(srt_path, proj_path).replace("\\", "/")
cmd = [
"ffmpeg",
"-i",
video_path, # Input video file
"-vf",
f"subtitles='{srt_path}':force_style='{style}'", # Apply subtitles with specified style
"-c:v",
"h264_nvenc", # Use NVIDIA NVENC for hardware-accelerated video encoding
"-preset",
"fast", # Use a fast encoding preset
"-c:a",
"copy", # Copy audio stream without re-encoding
out_path, # Output file path
]
subprocess.run(cmd, check=True)
os.replace(out_path, video_path) # 用输出文件替换原始文件
if __name__ == "__main__":
start_time = datetime.now()
asyncio.run(
generate_video(
audio_dir_path=r"C:\voice_and_srt\大道至簡",
image_path=r"E:\mjpics\剪映图片-大道至簡\*.png",
name="test",
video_dir_path=r"C:\videos\大道至簡",
)
)
# _add_caption(
# video_path=r"C:\videos\大道至簡\1.mp4",
# srt_path=r"C:\voice_and_srt\大道至簡\0.srt",
# )
end_time = datetime.now()
time_diff = end_time - start_time
print(f"Time difference: {time_diff}")
print(f"Seconds elapsed: {time_diff.total_seconds()} seconds")