ffmpeg.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. import subprocess
  2. import time
  3. from data_channel.data_help import dataHelp
  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. 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, new_video_path, video_path_url, pw_random_id):
  86. crop_url = video_path_url + str(pw_random_id) + '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", new_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, new_video_path, video_path_url, pw_random_id, gg_duration_total):
  111. gg_duration_url = video_path_url + str(pw_random_id) + 'gg_duration.mp4'
  112. # 获取视频时长
  113. total_duration = dataHelp.video_duration(new_video_path)
  114. # total_duration = cls.get_video_duration(new_video_path)
  115. duration = int(total_duration) - int(gg_duration_total)
  116. if int(total_duration) < int(gg_duration_total):
  117. return new_video_path
  118. ffmpeg_cmd = [
  119. "ffmpeg",
  120. "-i", new_video_path,
  121. "-c:v", "libx264",
  122. "-c:a", "aac",
  123. "-t", str(duration),
  124. "-y",
  125. gg_duration_url
  126. ]
  127. subprocess.run(ffmpeg_cmd)
  128. return gg_duration_url
  129. """
  130. 截取原视频最后一帧
  131. """
  132. @classmethod
  133. def video_png(cls, new_video_path, video_path_url, pw_random_id):
  134. """
  135. jpg_url 生成图片位置
  136. :param new_video_path: 视频地址
  137. :return:
  138. """
  139. # 获取视频的原始宽高信息
  140. jpg_url = video_path_url + str(pw_random_id) + 'png.jpg'
  141. # 获取视频时长
  142. total_duration = dataHelp.video_duration(new_video_path)
  143. time_offset = total_duration - 1 # 提取倒数第一秒的帧
  144. # 获取视频最后一秒,生成.jpg
  145. subprocess.run(
  146. ['ffmpeg', '-ss', str(time_offset), '-i', new_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, new_video_path, video_path_url, pw_random_id):
  168. video_h_w_path = video_path_url + str(pw_random_id) +'video_h_w_video.mp4'
  169. ffmpeg_cmd = f"ffmpeg -i {new_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. total_duration = dataHelp.video_duration(new_video_path)
  179. start_time = cls.seconds_to_srt_time(0)
  180. end_time = cls.seconds_to_srt_time(duration)
  181. # zm = '致敬伟大的教员,为整个民族\n感谢老人家历史向一代伟人'
  182. with open(single_video_txt, 'w') as f:
  183. f.write(f"file '{new_video_path}'\n")
  184. with open(single_video_srt, 'w') as f:
  185. f.write(f"1\n{start_time} --> {end_time}\n{new_text}\n\n")
  186. subtitle_cmd = f"subtitles={single_video_srt}:force_style='Fontsize=12,Fontname=wqy-zenhei,Outline=2,PrimaryColour=&H00FFFF,SecondaryColour=&H000000,Bold=1,MarginV=225'"
  187. draw = f"{subtitle_cmd}"
  188. ffmpeg_cmd = [
  189. "ffmpeg",
  190. "-f", "concat",
  191. "-safe", "0",
  192. "-i", single_video_txt,
  193. "-c:v", "libx264",
  194. "-c:a", "aac",
  195. # '-vf', f"scale=640x360",
  196. "-vf", draw,
  197. "-y",
  198. single_video
  199. ]
  200. subprocess.run(ffmpeg_cmd)
  201. return single_video
  202. """
  203. 生成片尾视频
  204. """
  205. @classmethod
  206. def pw_video(cls, jpg_url, video_path_url, pw_url, pw_srt, pw_random_id, pw_mp3_path):
  207. # 添加音频到图片
  208. """
  209. jpg_url 图片地址
  210. pw_video 提供的片尾视频
  211. pw_duration 提供的片尾视频时长
  212. new_video_path 视频位置
  213. subtitle_cmd 字幕
  214. pw_url 生成视频地址
  215. :return:
  216. """
  217. pw_srt_path = video_path_url + str(pw_random_id) +'pw_video.srt'
  218. # 创建临时字幕文件
  219. with open(pw_srt_path, 'w') as f:
  220. f.write(pw_srt)
  221. # 片尾位置
  222. pw_url_path = video_path_url + str(pw_random_id) + 'pw_video.mp4'
  223. # 获取视频时长
  224. pw_duration = dataHelp.video_duration(pw_url)
  225. # pw_duration = cls.get_video_duration(pw_url)
  226. time.sleep(2)
  227. # 添加字幕 wqy-zenhei Hiragino Sans GB
  228. height = 1080
  229. margin_v = int(height) // 8 # 可根据需要调整字幕和背景之间的距离
  230. 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}'"
  231. bg_position_offset = (int(360) - 360//8) / 1.75
  232. background_cmd = f"drawbox=y=(ih-{int(360)}/2-{bg_position_offset}):color=yellow@1.0:width=iw:height={int(360)}/4:t=fill"
  233. ffmpeg_cmd = [
  234. 'ffmpeg',
  235. '-loop', '1',
  236. '-i', jpg_url, # 输入的图片文件
  237. '-i', pw_mp3_path, # 输入的音频文件
  238. '-c:v', 'libx264', # 视频编码格式
  239. '-t', str(pw_duration), # 输出视频的持续时间,与音频持续时间相同
  240. '-pix_fmt', 'yuv420p', # 像素格式
  241. '-c:a', 'aac', # 音频编码格式
  242. '-strict', 'experimental', # 使用实验性编码器
  243. '-shortest', # 确保输出视频的长度与音频一致
  244. '-vf', f"{background_cmd},{subtitle_cmd}", # 视频过滤器,设置分辨率和其他过滤器
  245. pw_url_path # 输出的视频文件路径
  246. ]
  247. subprocess.run(ffmpeg_cmd)
  248. return pw_url_path
  249. """
  250. 设置统一格式拼接视频
  251. """
  252. @classmethod
  253. def concatenate_videos(cls, video_list, video_path_url):
  254. concatenate_videos_url = video_path_url + 'concatenate_videos.mp4'
  255. # 拼接视频
  256. VIDEO_COUNTER = 0
  257. FF_INPUT = ""
  258. FF_SCALE = ""
  259. FF_FILTER = ""
  260. ffmpeg_cmd = ["ffmpeg"]
  261. for videos in video_list:
  262. # 添加输入文件
  263. FF_INPUT += f" -i {videos}"
  264. # 为每个视频文件统一长宽,并设置SAR(采样宽高比)
  265. FF_SCALE += f"[{VIDEO_COUNTER}:v]scale=360x640,setsar=1[v{VIDEO_COUNTER}];"
  266. # 为每个视频文件创建一个输入流,并添加到-filter_complex参数中
  267. FF_FILTER += f"[v{VIDEO_COUNTER}][{VIDEO_COUNTER}:a]"
  268. # 增加视频计数器
  269. VIDEO_COUNTER += 1
  270. # 构建最终的FFmpeg命令
  271. ffmpeg_cmd.extend(FF_INPUT.split())
  272. ffmpeg_cmd.extend(["-filter_complex", f"{FF_SCALE}{FF_FILTER}concat=n={VIDEO_COUNTER}:v=1:a=1[v][a]",
  273. "-map", "[v]", "-map", "[a]", "-y", concatenate_videos_url])
  274. subprocess.run(ffmpeg_cmd)
  275. return concatenate_videos_url
  276. """
  277. 单个视频拼接
  278. """
  279. @classmethod
  280. def single_video(cls, new_video_path, video_path_url, zm):
  281. single_video_url = video_path_url + 'single_video.mp4'
  282. single_video_srt = video_path_url + 'single_video.srt'
  283. # 获取时长
  284. duration = dataHelp.video_duration(new_video_path)
  285. # duration = cls.get_video_duration(new_video_path)
  286. start_time = cls.seconds_to_srt_time(2)
  287. end_time = cls.seconds_to_srt_time(duration)
  288. single_video_txt = video_path_url + 'single_video.txt'
  289. with open(single_video_txt, 'w') as f:
  290. f.write(f"file '{new_video_path}'\n")
  291. height = 1080
  292. box_height = int(int(height) / 4) # 框的高度为视频高度的四分之一
  293. # background_cmd = f"drawbox=y=ih-{70 + box_height}-{int(box_height / 20)}:color=yellow@1.0:width=iw:height={box_height}:t=fill"
  294. if zm:
  295. # with open(single_video_srt, 'w') as f:
  296. # # f.write(f"1\n{start_time} --> {end_time}\n{zm}\n\n")
  297. # f.write(f"1\n{start_time} --> {end_time}\n<font color=\"red\">\u2764\uFE0F</font>{zm}\n\n")
  298. # subtitle_cmd = f"subtitles={single_video_srt}:force_style='Fontsize=12,Fontname=wqy-zenhei,Outline=2,PrimaryColour=&H00FFFF,SecondaryColour=&H000000,Bold=1,MarginV=10'"
  299. with open(single_video_srt, 'w') as f:
  300. # f.write(f"1\n{start_time} --> {end_time}\n\u2764\uFE0F{zm}\n\n")
  301. f.write(f"1\n{start_time} --> {end_time}\n<font color=\"red\">\u2764\uFE0F</font>{zm}\n\n")
  302. subtitle_cmd = f"subtitles={single_video_srt}:force_style='Fontsize=14,Fontname=wqy-zenhei,Outline=2,PrimaryColour=&H00FFFF,SecondaryColour=&H000000,Bold=1,MarginV=20'"
  303. else:
  304. subtitle_cmd = f"force_style='Fontsize=14,Fontname=wqy-zenhei,Outline=2,PrimaryColour=&H00FFFF,SecondaryColour=&H000000,Bold=1,MarginV=20'"
  305. draw = f"{subtitle_cmd}"
  306. # 多线程数
  307. num_threads = 5
  308. # 构建 FFmpeg 命令,生成视频
  309. ffmpeg_cmd_oss = [
  310. "ffmpeg",
  311. "-f", "concat",
  312. "-safe", "0",
  313. "-i", f"{single_video_txt}",
  314. "-c:v", "libx264",
  315. "-c:a", "aac",
  316. "-threads", str(num_threads),
  317. "-vf", f"{draw}",
  318. "-y",
  319. single_video_url
  320. ]
  321. subprocess.run(ffmpeg_cmd_oss)
  322. return single_video_url
  323. if __name__ == '__main__':
  324. new_video_path = '/Users/tzld/Desktop/video_rewriting/path/output1.mp4'
  325. video_path_url = '/Users/tzld/Desktop/video_rewriting/path/'
  326. zm = '温馨提示:下方按钮可分享到群'
  327. FFmpeg.single_video(new_video_path, video_path_url, zm)