ffmpeg.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. import subprocess
  2. import time
  3. class FFmpeg():
  4. """
  5. 时间转换
  6. """
  7. @classmethod
  8. def seconds_to_srt_time(cls, seconds):
  9. hours = int(seconds // 3600)
  10. minutes = int((seconds % 3600) // 60)
  11. seconds = seconds % 60
  12. milliseconds = int((seconds - int(seconds)) * 1000)
  13. return f"{hours:02d}:{minutes:02d}:{int(seconds):02d},{milliseconds:03d}"
  14. """
  15. 获取单个视频时长
  16. """
  17. @classmethod
  18. def get_video_duration(cls, video_url):
  19. ffprobe_cmd = [
  20. "ffprobe",
  21. "-i", video_url,
  22. "-show_entries", "format=duration",
  23. "-v", "quiet",
  24. "-of", "csv=p=0"
  25. ]
  26. output = subprocess.check_output(ffprobe_cmd).decode("utf-8").strip()
  27. return float(output)
  28. """
  29. 获取视频文件的时长(秒)
  30. """
  31. @classmethod
  32. def get_videos_duration(cls, video_file):
  33. result = subprocess.run(
  34. ["ffprobe", "-v", "error", "-show_entries", "format=duration",
  35. "-of", "default=noprint_wrappers=1:nokey=1", video_file],
  36. capture_output=True, text=True)
  37. return float(result.stdout)
  38. """
  39. 视频裁剪
  40. """
  41. @classmethod
  42. def video_tailor(cls, video_url):
  43. output_video_path = ''
  44. try:
  45. # 获取视频的原始宽高信息
  46. width, height = cls.get_w_h_size(video_url)
  47. # 计算裁剪后的高度
  48. new_height = int(height * 0.8)
  49. # 构建 FFmpeg 命令,裁剪视频高度为原始高度的70%,并将宽度缩放为320x480
  50. ffmpeg_cmd = [
  51. "ffmpeg",
  52. "-i", video_url,
  53. "-vf", f"crop={width}:{new_height},scale=320:480",
  54. "-c:v", "libx264",
  55. "-c:a", "aac",
  56. "-y",
  57. output_video_path
  58. ]
  59. # 执行 FFmpeg 命令
  60. subprocess.run(ffmpeg_cmd, check=True)
  61. return output_video_path
  62. except Exception as e:
  63. return None
  64. """
  65. 获取视频宽高
  66. """
  67. @classmethod
  68. def get_w_h_size(cls, new_video_path):
  69. try:
  70. # 获取视频的原始宽高信息
  71. ffprobe_cmd = f"ffprobe -v error -select_streams v:0 -show_entries stream=width,height -of csv=p=0 {new_video_path}"
  72. ffprobe_process = subprocess.Popen(ffprobe_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
  73. output, _ = ffprobe_process.communicate()
  74. output_decoded = output.decode().strip()
  75. split_output = [value for value in output_decoded.split(',') if value.strip()]
  76. height, width = map(int, split_output)
  77. return width, height
  78. except ValueError as e:
  79. return 1920, 1080
  80. """
  81. 视频裁剪
  82. """
  83. @classmethod
  84. def video_crop(cls, new_video_path, video_path_url, pw_random_id):
  85. crop_url = video_path_url + str(pw_random_id) + 'crop.mp4'
  86. # 获取视频的原始宽高信息
  87. ffprobe_cmd = f"ffprobe -v error -select_streams v:0 -show_entries stream=width,height -of csv=p=0 {new_video_path}"
  88. ffprobe_process = subprocess.Popen(ffprobe_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
  89. output, _ = ffprobe_process.communicate()
  90. width, height = map(int, output.decode().strip().split(','))
  91. # 计算裁剪后的高度
  92. new_height = int(height * 0.8)
  93. # 构建 FFmpeg 命令,裁剪视频高度为原始高度的80%
  94. ffmpeg_cmd = [
  95. "ffmpeg",
  96. "-i", new_video_path,
  97. "-vf", f"crop={width}:{new_height}",
  98. "-c:v", "libx264",
  99. "-c:a", "aac",
  100. "-y",
  101. crop_url
  102. ]
  103. subprocess.run(ffmpeg_cmd)
  104. return crop_url
  105. """
  106. 视频截断
  107. """
  108. @classmethod
  109. def video_ggduration(cls, new_video_path, video_path_url, pw_random_id, gg_duration_total):
  110. gg_duration_url = video_path_url + str(pw_random_id) + 'gg_duration.mp4'
  111. # 获取视频时长
  112. total_duration = cls.get_video_duration(new_video_path)
  113. duration = int(total_duration) - int(gg_duration_total)
  114. if int(total_duration) < int(gg_duration_total):
  115. return new_video_path
  116. ffmpeg_cmd = [
  117. "ffmpeg",
  118. "-i", new_video_path,
  119. "-c:v", "libx264",
  120. "-c:a", "aac",
  121. "-t", str(duration),
  122. "-y",
  123. gg_duration_url
  124. ]
  125. subprocess.run(ffmpeg_cmd)
  126. return gg_duration_url
  127. """
  128. 截取原视频最后一帧
  129. """
  130. @classmethod
  131. def video_png(cls, new_video_path, video_path_url, pw_random_id):
  132. """
  133. jpg_url 生成图片位置
  134. :param new_video_path: 视频地址
  135. :return:
  136. """
  137. # 获取视频的原始宽高信息
  138. jpg_url = video_path_url + str(pw_random_id) + 'png.jpg'
  139. # 获取视频时长
  140. total_duration = cls.get_video_duration(new_video_path)
  141. time_offset = total_duration - 1 # 提取倒数第一秒的帧
  142. # 获取视频最后一秒,生成.jpg
  143. subprocess.run(
  144. ['ffmpeg', '-ss', str(time_offset), '-i', new_video_path, '-t', str(total_duration), '-vf', 'fps=1', "-y", jpg_url])
  145. return jpg_url
  146. """
  147. 获取视频音频
  148. """
  149. @classmethod
  150. def get_video_mp3(cls, video_file, video_path_url, pw_random_id):
  151. pw_mp3_path = video_path_url + str(pw_random_id) +'pw_video.mp3'
  152. command = [
  153. 'ffmpeg',
  154. '-i', video_file,
  155. '-q:a', '0',
  156. '-map', 'a',
  157. # '-codec:a', 'libmp3lame', # 指定 MP3 编码器
  158. pw_mp3_path
  159. ]
  160. subprocess.run(command)
  161. time.sleep(1)
  162. return pw_mp3_path
  163. """横屏视频改为竖屏"""
  164. @classmethod
  165. def update_video_h_w(cls, new_video_path, video_path_url, pw_random_id):
  166. video_h_w_path = video_path_url + str(pw_random_id) +'video_h_w_video.mp4'
  167. ffmpeg_cmd = f"ffmpeg -i {new_video_path} -vf 'scale=1080:ih*1080/iw,pad=iw:iw*16/9:(ow-iw)/2:(oh-ih)/2' {video_h_w_path}"
  168. subprocess.run(ffmpeg_cmd, shell=True)
  169. return video_h_w_path
  170. """横屏视频顶部增加字幕"""
  171. @classmethod
  172. def add_video_zm(cls, new_video_path, video_path_url, pw_random_id, new_text):
  173. single_video_srt = video_path_url + str(pw_random_id) +'video_zm.srt'
  174. single_video_txt = video_path_url + str(pw_random_id) +'video_zm.txt'
  175. single_video = video_path_url + str(pw_random_id) +'video_zm.mp4'
  176. duration = cls.get_video_duration(new_video_path)
  177. start_time = cls.seconds_to_srt_time(0)
  178. end_time = cls.seconds_to_srt_time(duration)
  179. # zm = '致敬伟大的教员,为整个民族\n感谢老人家历史向一代伟人'
  180. with open(single_video_txt, 'w') as f:
  181. f.write(f"file '{new_video_path}'\n")
  182. with open(single_video_srt, 'w') as f:
  183. f.write(f"1\n{start_time} --> {end_time}\n{new_text}\n\n")
  184. subtitle_cmd = f"subtitles={single_video_srt}:force_style='Fontsize=12,Fontname=wqy-zenhei,Outline=2,PrimaryColour=&H00FFFF,SecondaryColour=&H000000,Bold=1,MarginV=225'"
  185. draw = f"{subtitle_cmd}"
  186. ffmpeg_cmd = [
  187. "ffmpeg",
  188. "-f", "concat",
  189. "-safe", "0",
  190. "-i", single_video_txt,
  191. "-c:v", "libx264",
  192. "-c:a", "aac",
  193. "-vf", draw,
  194. "-y",
  195. single_video
  196. ]
  197. subprocess.run(ffmpeg_cmd)
  198. return single_video
  199. """
  200. 生成片尾视频
  201. """
  202. @classmethod
  203. def pw_video(cls, jpg_url, video_path_url, pw_url, pw_srt, pw_random_id, pw_mp3_path):
  204. # 添加音频到图片
  205. """
  206. jpg_url 图片地址
  207. pw_video 提供的片尾视频
  208. pw_duration 提供的片尾视频时长
  209. new_video_path 视频位置
  210. subtitle_cmd 字幕
  211. pw_url 生成视频地址
  212. :return:
  213. """
  214. pw_srt_path = video_path_url + str(pw_random_id) +'pw_video.srt'
  215. # 创建临时字幕文件
  216. with open(pw_srt_path, 'w') as f:
  217. f.write(pw_srt)
  218. # 片尾位置
  219. pw_url_path = video_path_url + str(pw_random_id) + 'pw_video.mp4'
  220. # 获取视频时长
  221. pw_duration = cls.get_video_duration(pw_url)
  222. time.sleep(2)
  223. # 添加字幕 wqy-zenhei Hiragino Sans GB
  224. height = 1080
  225. margin_v = int(height) // 8 # 可根据需要调整字幕和背景之间的距离
  226. subtitle_cmd = f"subtitles={pw_srt_path}:force_style='Fontsize=13,Fontname=wqy-zenhei,Outline=0,PrimaryColour=&H000000,SecondaryColour=&H000000,Bold=1,MarginV={margin_v}'"
  227. bg_position_offset = (int(height) - margin_v) / 1.75
  228. background_cmd = f"drawbox=y=(ih-{int(height)}/2-{bg_position_offset}):color=yellow@1.0:width=iw:height={int(height)}/4:t=fill"
  229. ffmpeg_cmd = [
  230. 'ffmpeg',
  231. '-loop', '1',
  232. '-i', jpg_url, # 输入的图片文件
  233. '-i', pw_mp3_path, # 输入的音频文件
  234. '-c:v', 'libx264', # 视频编码格式
  235. '-t', str(pw_duration), # 输出视频的持续时间,与音频持续时间相同
  236. '-pix_fmt', 'yuv420p', # 像素格式
  237. '-c:a', 'aac', # 音频编码格式
  238. '-strict', 'experimental', # 使用实验性编码器
  239. '-shortest', # 确保输出视频的长度与音频一致
  240. '-vf', f"scale=1080x1920,{background_cmd},{subtitle_cmd}", # 视频过滤器,设置分辨率和其他过滤器
  241. pw_url_path # 输出的视频文件路径
  242. ]
  243. subprocess.run(ffmpeg_cmd)
  244. return pw_url_path
  245. """
  246. 设置统一格式拼接视频
  247. """
  248. @classmethod
  249. def concatenate_videos(cls, video_list, video_path_url):
  250. concatenate_videos_url = video_path_url + 'concatenate_videos.mp4'
  251. # 获取视频的原始宽高信息
  252. width, height = cls.get_w_h_size(video_list[0])
  253. # 拼接视频
  254. VIDEO_COUNTER = 0
  255. FF_INPUT = ""
  256. FF_SCALE = ""
  257. FF_FILTER = ""
  258. ffmpeg_cmd = ["ffmpeg"]
  259. for videos in video_list:
  260. # 添加输入文件
  261. FF_INPUT += f" -i {videos}"
  262. # 为每个视频文件统一长宽,并设置SAR(采样宽高比)
  263. FF_SCALE += f"[{VIDEO_COUNTER}:v]scale={int(height)}x{int(width)},setsar=1[v{VIDEO_COUNTER}];"
  264. # 为每个视频文件创建一个输入流,并添加到-filter_complex参数中
  265. FF_FILTER += f"[v{VIDEO_COUNTER}][{VIDEO_COUNTER}:a]"
  266. # 增加视频计数器
  267. VIDEO_COUNTER += 1
  268. # 构建最终的FFmpeg命令
  269. ffmpeg_cmd.extend(FF_INPUT.split())
  270. ffmpeg_cmd.extend(["-filter_complex", f"{FF_SCALE}{FF_FILTER}concat=n={VIDEO_COUNTER}:v=1:a=1[v][a]",
  271. "-map", "[v]", "-map", "[a]", "-y", concatenate_videos_url])
  272. subprocess.run(ffmpeg_cmd)
  273. return concatenate_videos_url
  274. """
  275. 单个视频拼接
  276. """
  277. @classmethod
  278. def single_video(cls, new_video_path, video_share, video_path_url, zm):
  279. single_video_url = video_path_url + 'single_video.mp4'
  280. single_video_srt = video_path_url + 'single_video.srt'
  281. # 获取时长
  282. duration = cls.get_video_duration(new_video_path)
  283. start_time = cls.seconds_to_srt_time(0)
  284. end_time = cls.seconds_to_srt_time(duration)
  285. single_video_txt = video_path_url + 'single_video.txt'
  286. with open(single_video_txt, 'w') as f:
  287. f.write(f"file '{new_video_path}'\n")
  288. with open(single_video_srt, 'w') as f:
  289. f.write(f"1\n{start_time} --> {end_time}\n\u2764\uFE0F{zm}\n\n")
  290. width, height = cls.get_w_h_size(new_video_path)
  291. box_height = int(int(height) / 4) # 框的高度为视频高度的四分之一
  292. background_cmd = f"drawbox=y=ih-{70 + box_height}-{int(box_height / 20)}:color=yellow@1.0:width=iw:height={box_height}:t=fill"
  293. if video_share == '有':
  294. # 添加字幕 wqy-zenhei Hiragino Sans GB
  295. subtitle_cmd = f"subtitles={single_video_srt}:force_style='Fontsize=14,Fontname=wqy-zenhei,Outline=0,PrimaryColour=&H000000,SecondaryColour=&H000000,Bold=1,MarginV=20'"
  296. draw = f"{background_cmd},{subtitle_cmd}"
  297. else:
  298. subtitle_cmd = f"subtitles={single_video_srt}:force_style='Fontsize=14,Fontname=wqy-zenhei,Outline=2,PrimaryColour=&H00FFFF,SecondaryColour=&H000000,Bold=1,MarginV=20'"
  299. draw = f"{subtitle_cmd}"
  300. # 多线程数
  301. num_threads = 5
  302. # 构建 FFmpeg 命令,生成视频
  303. ffmpeg_cmd_oss = [
  304. "ffmpeg",
  305. "-f", "concat",
  306. "-safe", "0",
  307. "-i", f"{single_video_txt}",
  308. "-c:v", "libx264",
  309. "-c:a", "aac",
  310. "-threads", str(num_threads),
  311. "-vf", f"{draw}",
  312. "-y",
  313. single_video_url
  314. ]
  315. subprocess.run(ffmpeg_cmd_oss)
  316. return single_video_url