ffmpeg.py 11 KB

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