ffmpeg.py 14 KB

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