ffmpeg.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  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. 生成片尾视频
  165. """
  166. @classmethod
  167. def pw_video(cls, jpg_url, video_path_url, pw_url, pw_srt, pw_random_id, pw_mp3_path):
  168. # 添加音频到图片
  169. """
  170. jpg_url 图片地址
  171. pw_video 提供的片尾视频
  172. pw_duration 提供的片尾视频时长
  173. new_video_path 视频位置
  174. subtitle_cmd 字幕
  175. pw_url 生成视频地址
  176. :return:
  177. """
  178. pw_srt_path = video_path_url + str(pw_random_id) +'pw_video.srt'
  179. # 创建临时字幕文件
  180. with open(pw_srt_path, 'w') as f:
  181. f.write(pw_srt)
  182. # 片尾位置
  183. pw_url_path = video_path_url + str(pw_random_id) + 'pw_video.mp4'
  184. # 获取视频时长
  185. pw_duration = cls.get_video_duration(pw_url)
  186. time.sleep(2)
  187. # 添加字幕 wqy-zenhei Hiragino Sans GB
  188. height = 1080
  189. margin_v = int(height) // 8 # 可根据需要调整字幕和背景之间的距离
  190. subtitle_cmd = f"subtitles={pw_srt_path}:force_style='Fontsize=14,Fontname=wqy-zenhei,Outline=0,PrimaryColour=&H000000,SecondaryColour=&H000000,Bold=1,MarginV={margin_v}'"
  191. bg_position_offset = (int(height) - margin_v) / 1.75
  192. background_cmd = f"drawbox=y=(ih-{int(height)}/2-{bg_position_offset}):color=yellow@1.0:width=iw:height={int(height)}/4:t=fill"
  193. ffmpeg_cmd = [
  194. 'ffmpeg',
  195. '-loop', '1',
  196. '-i', jpg_url, # 输入的图片文件
  197. '-i', pw_mp3_path, # 输入的音频文件
  198. '-c:v', 'libx264', # 视频编码格式
  199. '-t', str(pw_duration), # 输出视频的持续时间,与音频持续时间相同
  200. '-pix_fmt', 'yuv420p', # 像素格式
  201. '-c:a', 'aac', # 音频编码格式
  202. '-strict', 'experimental', # 使用实验性编码器
  203. '-shortest', # 确保输出视频的长度与音频一致
  204. '-vf', f"scale=1080x1920,{background_cmd},{subtitle_cmd}", # 视频过滤器,设置分辨率和其他过滤器
  205. pw_url_path # 输出的视频文件路径
  206. ]
  207. subprocess.run(ffmpeg_cmd)
  208. return pw_url_path
  209. """
  210. 设置统一格式拼接视频
  211. """
  212. @classmethod
  213. def concatenate_videos(cls, video_list, video_path_url):
  214. concatenate_videos_url = video_path_url + 'concatenate_videos.mp4'
  215. # 获取视频的原始宽高信息
  216. width, height = cls.get_w_h_size(video_list[0])
  217. # 拼接视频
  218. VIDEO_COUNTER = 0
  219. FF_INPUT = ""
  220. FF_SCALE = ""
  221. FF_FILTER = ""
  222. ffmpeg_cmd = ["ffmpeg"]
  223. for videos in video_list:
  224. # 添加输入文件
  225. FF_INPUT += f" -i {videos}"
  226. # 为每个视频文件统一长宽,并设置SAR(采样宽高比)
  227. FF_SCALE += f"[{VIDEO_COUNTER}:v]scale={int(height)}x{int(width)},setsar=1[v{VIDEO_COUNTER}];"
  228. # 为每个视频文件创建一个输入流,并添加到-filter_complex参数中
  229. FF_FILTER += f"[v{VIDEO_COUNTER}][{VIDEO_COUNTER}:a]"
  230. # 增加视频计数器
  231. VIDEO_COUNTER += 1
  232. # 构建最终的FFmpeg命令
  233. ffmpeg_cmd.extend(FF_INPUT.split())
  234. ffmpeg_cmd.extend(["-filter_complex", f"{FF_SCALE}{FF_FILTER}concat=n={VIDEO_COUNTER}:v=1:a=1[v][a]",
  235. "-map", "[v]", "-map", "[a]", "-y", concatenate_videos_url])
  236. subprocess.run(ffmpeg_cmd)
  237. return concatenate_videos_url
  238. """
  239. 单个视频拼接
  240. """
  241. @classmethod
  242. def single_video(cls, new_video_path, video_share, video_path_url, zm):
  243. single_video_url = video_path_url + 'single_video.mp4'
  244. single_video_srt = video_path_url + 'single_video.srt'
  245. # 获取时长
  246. duration = cls.get_video_duration(new_video_path)
  247. start_time = cls.seconds_to_srt_time(0)
  248. end_time = cls.seconds_to_srt_time(duration)
  249. single_video_txt = video_path_url + 'single_video.txt'
  250. with open(single_video_txt, 'w') as f:
  251. f.write(f"file '{new_video_path}'\n")
  252. with open(single_video_srt, 'w') as f:
  253. f.write(f"1\n{start_time} --> {end_time}\n\u2764\uFE0F{zm}\n\n")
  254. width, height = cls.get_w_h_size(new_video_path)
  255. box_height = int(int(height) / 4) # 框的高度为视频高度的四分之一
  256. background_cmd = f"drawbox=y=ih-{70 + box_height}-{int(box_height / 20)}:color=yellow@1.0:width=iw:height={box_height}:t=fill"
  257. if video_share == '有':
  258. # 添加字幕 wqy-zenhei Hiragino Sans GB
  259. subtitle_cmd = f"subtitles={single_video_srt}:force_style='Fontsize=14,Fontname=wqy-zenhei,Outline=0,PrimaryColour=&H000000,SecondaryColour=&H000000,Bold=1,MarginV=20'"
  260. draw = f"{background_cmd},{subtitle_cmd}"
  261. else:
  262. subtitle_cmd = f"subtitles={single_video_srt}:force_style='Fontsize=14,Fontname=wqy-zenhei,Outline=2,PrimaryColour=&H00FFFF,SecondaryColour=&H000000,Bold=1,MarginV=20'"
  263. draw = f"{subtitle_cmd}"
  264. # 多线程数
  265. num_threads = 4
  266. # 构建 FFmpeg 命令,生成视频
  267. ffmpeg_cmd_oss = [
  268. "ffmpeg",
  269. "-f", "concat",
  270. "-safe", "0",
  271. "-i", f"{single_video_txt}",
  272. "-c:v", "libx264",
  273. "-c:a", "aac",
  274. "-threads", str(num_threads),
  275. "-vf", f"{draw}",
  276. "-y",
  277. single_video_url
  278. ]
  279. subprocess.run(ffmpeg_cmd_oss)
  280. return single_video_url