ffmpeg.py 13 KB

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