ffmpeg_helper.go 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888
  1. package ffmpeg_helper
  2. import (
  3. "bytes"
  4. "errors"
  5. "fmt"
  6. "os"
  7. "os/exec"
  8. "path/filepath"
  9. "strconv"
  10. "github.com/allanpk716/ChineseSubFinder/pkg"
  11. "github.com/allanpk716/ChineseSubFinder/pkg/types/common"
  12. "github.com/allanpk716/ChineseSubFinder/pkg/language"
  13. "github.com/allanpk716/ChineseSubFinder/pkg/logic/sub_parser/ass"
  14. "github.com/allanpk716/ChineseSubFinder/pkg/logic/sub_parser/srt"
  15. "github.com/allanpk716/ChineseSubFinder/pkg/sub_parser_hub"
  16. "github.com/sirupsen/logrus"
  17. "github.com/tidwall/gjson"
  18. "strings"
  19. )
  20. type FFMPEGHelper struct {
  21. log *logrus.Logger
  22. SubParserHub *sub_parser_hub.SubParserHub // 字幕内容的解析器
  23. }
  24. func NewFFMPEGHelper(log *logrus.Logger) *FFMPEGHelper {
  25. return &FFMPEGHelper{
  26. log: log,
  27. SubParserHub: sub_parser_hub.NewSubParserHub(log, ass.NewParser(log), srt.NewParser(log)),
  28. }
  29. }
  30. // Version 获取版本信息,如果不存在 FFMPEG 和 ffprobe 则报错
  31. func (f *FFMPEGHelper) Version() (string, error) {
  32. outMsg0, err := f.getVersion("ffmpeg")
  33. if err != nil {
  34. return "", err
  35. }
  36. outMsg1, err := f.getVersion("ffprobe")
  37. if err != nil {
  38. return "", err
  39. }
  40. return outMsg0 + "\r\n" + outMsg1, nil
  41. }
  42. // GetFFMPEGInfo 获取 视频的 FFMPEG 信息,包含音频和字幕
  43. // 优先会导出 中、英、日、韩 类型的,字幕如果没有语言类型,则也导出,然后需要额外的字幕语言的判断去辅助标记(读取文件内容)
  44. // 音频只会导出一个,优先导出 中、英、日、韩 类型的
  45. func (f *FFMPEGHelper) GetFFMPEGInfo(videoFileFullPath string, exportType ExportType) (bool, *FFMPEGInfo, error) {
  46. const args = "-v error -show_format -show_streams -print_format json"
  47. cmdArgs := strings.Fields(args)
  48. cmdArgs = append(cmdArgs, videoFileFullPath)
  49. cmd := exec.Command("ffprobe", cmdArgs...)
  50. buf := bytes.NewBufferString("")
  51. //指定输出位置
  52. cmd.Stderr = buf
  53. cmd.Stdout = buf
  54. err := cmd.Start()
  55. if err != nil {
  56. return false, nil, err
  57. }
  58. err = cmd.Wait()
  59. if err != nil {
  60. return false, nil, err
  61. }
  62. // 解析得到的字符串反馈
  63. bok, ffMPEGInfo, _ := f.parseJsonString2GetFFProbeInfo(videoFileFullPath, buf.String())
  64. if bok == false {
  65. return false, nil, nil
  66. }
  67. nowCacheFolderPath, err := ffMPEGInfo.GetCacheFolderFPath()
  68. if err != nil {
  69. return false, nil, err
  70. }
  71. // 在函数调用完毕后,判断是否需要清理
  72. defer func() {
  73. if bok == false && ffMPEGInfo != nil {
  74. err := os.RemoveAll(nowCacheFolderPath)
  75. if err != nil {
  76. f.log.Errorln("GetFFMPEGInfo - RemoveAll", err.Error())
  77. return
  78. }
  79. }
  80. }()
  81. // 查找当前这个视频外置字幕列表
  82. err = ffMPEGInfo.GetExternalSubInfos(f.SubParserHub)
  83. if err != nil {
  84. return false, nil, err
  85. }
  86. ffMPEGInfo.Duration = f.getVideoDuration(videoFileFullPath)
  87. // 判断这个视频是否已经导出过内置的字幕和音频文件了
  88. if ffMPEGInfo.IsExported(exportType) == false {
  89. // 说明缓存不存在,需要导出,这里需要注意,如果导出失败了,这个文件夹要清理掉
  90. if pkg.IsDir(nowCacheFolderPath) == true {
  91. // 如果存在则,先清空一个这个文件夹
  92. err = pkg.ClearFolder(nowCacheFolderPath)
  93. if err != nil {
  94. bok = false
  95. return bok, nil, err
  96. }
  97. }
  98. // 开始导出
  99. // 构建导出的命令参数
  100. exportAudioArgs, exportSubArgs := f.getAudioAndSubExportArgs(videoFileFullPath, ffMPEGInfo)
  101. // 上面导出的信息,可能是 nil 参数,那么就直接把导出的 List 信息给置为 nil,让后续有依据可以跳出,不继续执行
  102. if exportType == Subtitle {
  103. if exportSubArgs == nil {
  104. ffMPEGInfo.SubtitleInfoList = nil
  105. return true, ffMPEGInfo, nil
  106. }
  107. } else if exportType == Audio {
  108. if exportAudioArgs == nil {
  109. ffMPEGInfo.AudioInfoList = nil
  110. return true, ffMPEGInfo, nil
  111. }
  112. } else if exportType == SubtitleAndAudio {
  113. if exportAudioArgs == nil || exportSubArgs == nil {
  114. if exportAudioArgs == nil {
  115. ffMPEGInfo.AudioInfoList = nil
  116. }
  117. if exportSubArgs == nil {
  118. ffMPEGInfo.SubtitleInfoList = nil
  119. }
  120. return true, ffMPEGInfo, nil
  121. }
  122. } else {
  123. f.log.Errorln("GetFFMPEGInfo.getAudioAndSubExportArgs Not Support ExportType")
  124. return false, nil, nil
  125. }
  126. // 上面的操作为了就是确保后续的导出不会出问题
  127. // 执行导出,音频和内置的字幕
  128. execErrorString, err := f.exportAudioAndSubtitles(exportAudioArgs, exportSubArgs, exportType)
  129. if err != nil {
  130. f.log.Errorln("exportAudioAndSubtitles", execErrorString)
  131. bok = false
  132. return bok, nil, err
  133. }
  134. // 导出后,需要把现在导出的文件的路径给复制给 ffMPEGInfo 中
  135. // 音频是否导出了
  136. ffMPEGInfo.isAudioExported(nowCacheFolderPath)
  137. // 字幕都要导出了
  138. ffMPEGInfo.isSubExported(nowCacheFolderPath)
  139. // 创建 exportedMakeFileName 这个文件
  140. // 成功,那么就需要生成这个 exportedMakeFileName 文件
  141. err = ffMPEGInfo.CreateExportedMask()
  142. if err != nil {
  143. return false, nil, err
  144. }
  145. }
  146. return bok, ffMPEGInfo, nil
  147. }
  148. // GetAudioDurationInfo 获取音频的长度信息
  149. func (f *FFMPEGHelper) GetAudioDurationInfo(audioFileFullPath string) (bool, float64, error) {
  150. const args = "-v error -show_format -show_streams -print_format json -f s16le -ac 1 -ar 16000"
  151. cmdArgs := strings.Fields(args)
  152. cmdArgs = append(cmdArgs, audioFileFullPath)
  153. cmd := exec.Command("ffprobe", cmdArgs...)
  154. buf := bytes.NewBufferString("")
  155. //指定输出位置
  156. cmd.Stderr = buf
  157. cmd.Stdout = buf
  158. err := cmd.Start()
  159. if err != nil {
  160. return false, 0, err
  161. }
  162. err = cmd.Wait()
  163. if err != nil {
  164. return false, 0, err
  165. }
  166. bok, duration := f.parseJsonString2GetAudioInfo(buf.String())
  167. if bok == false {
  168. return false, 0, errors.New("ffprobe get " + audioFileFullPath + " duration error")
  169. }
  170. return true, duration, nil
  171. }
  172. // ExportAudioAndSubArgsByTimeRange 根据输入的时间轴导出音频分段信息 "0:1:27" "28.2"
  173. func (f *FFMPEGHelper) ExportAudioAndSubArgsByTimeRange(audioFullPath, subFullPath string, startTimeString, timeLength string) (string, string, string, error) {
  174. outStartTimeString := strings.ReplaceAll(startTimeString, ":", "-")
  175. outStartTimeString = strings.ReplaceAll(outStartTimeString, ".", "#")
  176. outTimeLength := strings.ReplaceAll(timeLength, ".", "#")
  177. frontName := strings.ReplaceAll(filepath.Base(audioFullPath), filepath.Ext(audioFullPath), "")
  178. outAudioName := frontName + "_" + outStartTimeString + "_" + outTimeLength + filepath.Ext(audioFullPath)
  179. outSubName := frontName + "_" + outStartTimeString + "_" + outTimeLength + common.SubExtSRT
  180. var outAudioFullPath = filepath.Join(filepath.Dir(audioFullPath), outAudioName)
  181. var outSubFullPath = filepath.Join(filepath.Dir(audioFullPath), outSubName)
  182. // 导出音频
  183. if pkg.IsFile(outAudioFullPath) == true {
  184. err := os.Remove(outAudioFullPath)
  185. if err != nil {
  186. return "", "", "", err
  187. }
  188. }
  189. args := f.getAudioExportArgsByTimeRange(audioFullPath, startTimeString, timeLength, outAudioFullPath)
  190. execFFMPEG, err := f.execFFMPEG(args)
  191. if err != nil {
  192. return "", "", execFFMPEG, err
  193. }
  194. // 导出字幕
  195. if pkg.IsFile(outSubFullPath) == true {
  196. err := os.Remove(outSubFullPath)
  197. if err != nil {
  198. return "", "", "", err
  199. }
  200. }
  201. args = f.getSubExportArgsByTimeRange(subFullPath, startTimeString, timeLength, outSubFullPath)
  202. execFFMPEG, err = f.execFFMPEG(args)
  203. if err != nil {
  204. return "", "", execFFMPEG, err
  205. }
  206. return outAudioFullPath, outSubFullPath, "", nil
  207. }
  208. // ExportSubArgsByTimeRange 根据输入的时间轴导出字幕分段信息 "0:1:27" "28.2"
  209. func (f *FFMPEGHelper) ExportSubArgsByTimeRange(subFullPath, outName string, startTimeString, timeLength string) (string, string, error) {
  210. outStartTimeString := strings.ReplaceAll(startTimeString, ":", "-")
  211. outStartTimeString = strings.ReplaceAll(outStartTimeString, ".", "#")
  212. outTimeLength := strings.ReplaceAll(timeLength, ".", "#")
  213. frontName := strings.ReplaceAll(filepath.Base(subFullPath), filepath.Ext(subFullPath), "")
  214. outSubName := frontName + "_" + outStartTimeString + "_" + outTimeLength + "_" + outName + common.SubExtSRT
  215. var outSubFullPath = filepath.Join(filepath.Dir(subFullPath), outSubName)
  216. // 导出字幕
  217. if pkg.IsFile(outSubFullPath) == true {
  218. err := os.Remove(outSubFullPath)
  219. if err != nil {
  220. return "", "", err
  221. }
  222. }
  223. args := f.getSubExportArgsByTimeRange(subFullPath, startTimeString, timeLength, outSubFullPath)
  224. execFFMPEG, err := f.execFFMPEG(args)
  225. if err != nil {
  226. return "", execFFMPEG, err
  227. }
  228. return outSubFullPath, "", nil
  229. }
  230. // ExportVideoHLSAndSubByTimeRange 导出指定的时间轴的视频HLS和字幕,然后从 outDirPath 中获取 outputlist.m3u8 和字幕的文件
  231. func (f *FFMPEGHelper) ExportVideoHLSAndSubByTimeRange(videoFullPath, subFullPath, startTimeString, timeLength, segmentTime, outDirPath string) error {
  232. // 导出视频
  233. if pkg.IsFile(videoFullPath) == false {
  234. return errors.New("video file not exist, maybe is bluray file, so not support yet")
  235. }
  236. fileName := filepath.Base(videoFullPath)
  237. frontName := strings.ReplaceAll(fileName, filepath.Ext(fileName), "")
  238. if pkg.IsDir(outDirPath) == true {
  239. err := os.RemoveAll(outDirPath)
  240. if err != nil {
  241. return err
  242. }
  243. }
  244. err := os.MkdirAll(outDirPath, os.ModePerm)
  245. if err != nil {
  246. return err
  247. }
  248. //// 先剪切
  249. //videoExt := filepath.Ext(fileName)
  250. //cutOffVideoFPath := filepath.Join(outDirPath, frontName+"_cut"+videoExt)
  251. //args := f.getVideoExportArgsByTimeRange(videoFullPath, startTimeString, timeLength, cutOffVideoFPath)
  252. //execFFMPEG, err := f.execFFMPEG(args)
  253. //if err != nil {
  254. // return errors.New(execFFMPEG + err.Error())
  255. //}
  256. //// 转换 HLS
  257. //args = f.getVideo2HLSArgs(cutOffVideoFPath, segmentTime, outDirPath)
  258. //execFFMPEG, err = f.execFFMPEG(args)
  259. //if err != nil {
  260. // return errors.New(execFFMPEG + err.Error())
  261. //}
  262. // 直接导出
  263. args := f.getVideoHLSExportArgsByTimeRange(videoFullPath, startTimeString, timeLength, segmentTime, outDirPath)
  264. execFFMPEG, err := f.execFFMPEG(args)
  265. if err != nil {
  266. return errors.New(execFFMPEG + err.Error())
  267. }
  268. // 导出字幕
  269. nowSubExt := filepath.Ext(subFullPath)
  270. outSubFileFPath := filepath.Join(outDirPath, frontName+nowSubExt)
  271. args = f.getSubExportArgsByTimeRange(subFullPath, startTimeString, timeLength, outSubFileFPath)
  272. execFFMPEG, err = f.execFFMPEG(args)
  273. if err != nil {
  274. return errors.New(execFFMPEG + err.Error())
  275. }
  276. return nil
  277. }
  278. // parseJsonString2GetFFProbeInfo 使用 ffprobe 获取视频的 stream 信息,从中解析出字幕和音频的索引
  279. func (f *FFMPEGHelper) parseJsonString2GetFFProbeInfo(videoFileFullPath, inputFFProbeString string) (bool, *FFMPEGInfo, *FFMPEGInfo) {
  280. streamsValue := gjson.Get(inputFFProbeString, "streams.#")
  281. if streamsValue.Exists() == false {
  282. return false, nil, nil
  283. }
  284. ffmpegInfoFlitter := NewFFMPEGInfo(f.log, videoFileFullPath)
  285. ffmpegInfoFull := NewFFMPEGInfo(f.log, videoFileFullPath)
  286. // 进行字幕和音频的缓存,优先当然是导出 中、英、日、韩 相关的字幕和音频
  287. // 但是如果都没得这些的时候,那么也需要导出至少一个字幕或者音频,用于字幕的校正
  288. cacheAudios := make([]AudioInfo, 0)
  289. cacheSubtitleInfos := make([]SubtitleInfo, 0)
  290. for i := 0; i < int(streamsValue.Num); i++ {
  291. oneIndex := gjson.Get(inputFFProbeString, fmt.Sprintf("streams.%d.index", i))
  292. oneCodecName := gjson.Get(inputFFProbeString, fmt.Sprintf("streams.%d.codec_name", i))
  293. oneCodecType := gjson.Get(inputFFProbeString, fmt.Sprintf("streams.%d.codec_type", i))
  294. oneTimeBase := gjson.Get(inputFFProbeString, fmt.Sprintf("streams.%d.time_base", i))
  295. oneStartTime := gjson.Get(inputFFProbeString, fmt.Sprintf("streams.%d.start_time", i))
  296. oneLanguage := gjson.Get(inputFFProbeString, fmt.Sprintf("streams.%d.tags.language", i))
  297. // 任意一个字段不存在则跳过
  298. if oneIndex.Exists() == false {
  299. continue
  300. }
  301. if oneCodecName.Exists() == false {
  302. continue
  303. }
  304. if oneCodecType.Exists() == false {
  305. continue
  306. }
  307. if oneTimeBase.Exists() == false {
  308. continue
  309. }
  310. if oneStartTime.Exists() == false {
  311. continue
  312. }
  313. // 这里需要区分是字幕还是音频
  314. if oneCodecType.String() == codecTypeSub {
  315. // 字幕
  316. // 只解析 subrip 类型的,不支持 hdmv_pgs_subtitle 的字幕导出
  317. if f.isSupportSubCodecName(oneCodecName.String()) == false {
  318. continue
  319. }
  320. // 这里非必须解析到 language 字段,把所有的都导出来,然后通过额外字幕语言判断即可
  321. oneDurationTS := gjson.Get(inputFFProbeString, fmt.Sprintf("streams.%d.duration_ts", i))
  322. oneDuration := gjson.Get(inputFFProbeString, fmt.Sprintf("streams.%d.duration", i))
  323. // 必须存在的
  324. if oneDurationTS.Exists() == false {
  325. continue
  326. }
  327. if oneDuration.Exists() == false {
  328. continue
  329. }
  330. // 非必须存在的
  331. nowLanguageString := ""
  332. if oneLanguage.Exists() == true {
  333. nowLanguageString = oneLanguage.String()
  334. // 只导出 中、英、日、韩
  335. if language.IsSupportISOString(nowLanguageString) == false {
  336. subInfo := NewSubtitleInfo(int(oneIndex.Num), oneCodecName.String(), oneCodecType.String(),
  337. oneTimeBase.String(), oneStartTime.String(),
  338. int(oneDurationTS.Num), oneDuration.String(), nowLanguageString)
  339. // 不符合的也存在下来,万一,符合要求的一个都没得的时候,就需要从里面挑几个出来了
  340. cacheSubtitleInfos = append(cacheSubtitleInfos, *subInfo)
  341. continue
  342. }
  343. }
  344. subInfo := NewSubtitleInfo(int(oneIndex.Num), oneCodecName.String(), oneCodecType.String(),
  345. oneTimeBase.String(), oneStartTime.String(),
  346. int(oneDurationTS.Num), oneDuration.String(), nowLanguageString)
  347. ffmpegInfoFlitter.SubtitleInfoList = append(ffmpegInfoFlitter.SubtitleInfoList, *subInfo)
  348. } else if oneCodecType.String() == codecTypeAudio {
  349. // 音频
  350. // 这里必要要能够解析到 language 字段
  351. if oneLanguage.Exists() == false {
  352. // 不符合的也存在下来,万一,符合要求的一个都没得的时候,就需要从里面挑几个出来了
  353. audioInfo := NewAudioInfo(int(oneIndex.Num), oneCodecName.String(), oneCodecType.String(),
  354. oneTimeBase.String(), oneStartTime.String(), oneLanguage.String())
  355. cacheAudios = append(cacheAudios, *audioInfo)
  356. continue
  357. }
  358. // 只导出 中、英、日、韩
  359. if language.IsSupportISOString(oneLanguage.String()) == false {
  360. // 不符合的也存在下来,万一,符合要求的一个都没得的时候,就需要从里面挑几个出来了
  361. audioInfo := NewAudioInfo(int(oneIndex.Num), oneCodecName.String(), oneCodecType.String(),
  362. oneTimeBase.String(), oneStartTime.String(), oneLanguage.String())
  363. cacheAudios = append(cacheAudios, *audioInfo)
  364. continue
  365. }
  366. audioInfo := NewAudioInfo(int(oneIndex.Num), oneCodecName.String(), oneCodecType.String(),
  367. oneTimeBase.String(), oneStartTime.String(), oneLanguage.String())
  368. ffmpegInfoFlitter.AudioInfoList = append(ffmpegInfoFlitter.AudioInfoList, *audioInfo)
  369. } else {
  370. continue
  371. }
  372. }
  373. // 把过滤的和缓存的都拼接到一起
  374. for _, audioInfo := range ffmpegInfoFlitter.AudioInfoList {
  375. ffmpegInfoFull.AudioInfoList = append(ffmpegInfoFull.AudioInfoList, audioInfo)
  376. }
  377. for _, audioInfo := range cacheAudios {
  378. ffmpegInfoFull.AudioInfoList = append(ffmpegInfoFull.AudioInfoList, audioInfo)
  379. }
  380. for _, subInfo := range ffmpegInfoFlitter.SubtitleInfoList {
  381. ffmpegInfoFull.SubtitleInfoList = append(ffmpegInfoFull.SubtitleInfoList, subInfo)
  382. }
  383. for _, subInfo := range cacheSubtitleInfos {
  384. ffmpegInfoFull.SubtitleInfoList = append(ffmpegInfoFull.SubtitleInfoList, subInfo)
  385. }
  386. // 如何没有找到合适的字幕,那么就要把缓存的字幕选一个填充进去
  387. if len(ffmpegInfoFlitter.SubtitleInfoList) == 0 {
  388. if len(cacheSubtitleInfos) != 0 {
  389. ffmpegInfoFlitter.SubtitleInfoList = append(ffmpegInfoFlitter.SubtitleInfoList, cacheSubtitleInfos[0])
  390. }
  391. }
  392. // 如何没有找到合适的音频,那么就要把缓存的音频选一个填充进去
  393. if len(ffmpegInfoFlitter.AudioInfoList) == 0 {
  394. if len(cacheAudios) != 0 {
  395. ffmpegInfoFlitter.AudioInfoList = append(ffmpegInfoFlitter.AudioInfoList, cacheAudios[0])
  396. }
  397. } else {
  398. // 音频只需要导出一个就行了,取第一个
  399. newAudioList := make([]AudioInfo, 0)
  400. newAudioList = append(newAudioList, ffmpegInfoFlitter.AudioInfoList[0])
  401. ffmpegInfoFlitter.AudioInfoList = newAudioList
  402. }
  403. return true, ffmpegInfoFlitter, ffmpegInfoFull
  404. }
  405. // parseJsonString2GetAudioInfo 获取 pcm 音频的长度
  406. func (f *FFMPEGHelper) parseJsonString2GetAudioInfo(inputFFProbeString string) (bool, float64) {
  407. durationValue := gjson.Get(inputFFProbeString, "format.duration")
  408. if durationValue.Exists() == false {
  409. return false, 0
  410. }
  411. return true, durationValue.Float()
  412. }
  413. // exportAudioAndSubtitles 导出音频和字幕文件
  414. func (f *FFMPEGHelper) exportAudioAndSubtitles(audioArgs, subArgs []string, exportType ExportType) (string, error) {
  415. // 输入的两个数组,有可能是 nil
  416. // 这里导出依赖的是 ffmpeg 这个程序,需要的是构建导出的语句
  417. if exportType == SubtitleAndAudio {
  418. execErrorString, err := f.execFFMPEG(audioArgs)
  419. if err != nil {
  420. return execErrorString, err
  421. }
  422. execErrorString, err = f.execFFMPEG(subArgs)
  423. if err != nil {
  424. return execErrorString, err
  425. }
  426. } else if exportType == Audio {
  427. execErrorString, err := f.execFFMPEG(audioArgs)
  428. if err != nil {
  429. return execErrorString, err
  430. }
  431. } else if exportType == Subtitle {
  432. execErrorString, err := f.execFFMPEG(subArgs)
  433. if err != nil {
  434. return execErrorString, err
  435. }
  436. } else {
  437. return "", errors.New("FFMPEGHelper ExportType not support")
  438. }
  439. return "", nil
  440. }
  441. // execFFMPEG 执行 ffmpeg 命令
  442. func (f *FFMPEGHelper) execFFMPEG(cmds []string) (string, error) {
  443. if cmds == nil || len(cmds) == 0 {
  444. return "", nil
  445. }
  446. cmd := exec.Command("ffmpeg", cmds...)
  447. buf := bytes.NewBufferString("")
  448. //指定输出位置
  449. cmd.Stderr = buf
  450. cmd.Stdout = buf
  451. err := cmd.Start()
  452. if err != nil {
  453. return buf.String(), err
  454. }
  455. err = cmd.Wait()
  456. if err != nil {
  457. return buf.String(), err
  458. }
  459. return "", nil
  460. }
  461. // getAudioAndSubExportArgs 构建从原始视频导出字幕、音频的 ffmpeg 的参数 audioArgs, subArgs
  462. func (f *FFMPEGHelper) getAudioAndSubExportArgs(videoFileFullPath string, ffmpegInfo *FFMPEGInfo) ([]string, []string) {
  463. /*
  464. 导出多个字幕
  465. ffmpeg.exe -i xx.mp4 -vn -an -map 0:7 subs-7.srt -map 0:6 subs-6.srt
  466. 导出音频,从 1m 27s 开始,导出向后的 28 s,转换为 mp3 格式
  467. ffmpeg.exe -i xx.mp4 -vn -map 0:1 -ss 00:1:27 -f mp3 -t 28 audio.mp3
  468. 导出音频,转换为 mp3 格式
  469. ffmpeg.exe -i xx.mp4 -vn -map 0:1 -f mp3 audio.mp3
  470. 导出音频,转换为 16000k 16bit 单通道 采样率的 test.pcm
  471. ffmpeg.exe -i xx.mp4 -vn -map 0:1 -ss 00:1:27 -t 28 -acodec pcm_s16le -f s16le -ac 1 -ar 16000 test.pcm
  472. 截取字幕的时间片段
  473. ffmpeg.exe -i "subs-3.srt" -ss 00:1:27 -t 28 subs-3-cut-from-org.srt
  474. */
  475. var subArgs = make([]string, 0)
  476. var audioArgs = make([]string, 0)
  477. // 基础的输入视频参数
  478. subArgs = append(subArgs, "-i")
  479. audioArgs = append(audioArgs, "-i")
  480. subArgs = append(subArgs, videoFileFullPath)
  481. audioArgs = append(audioArgs, videoFileFullPath)
  482. // 字幕导出的参数构建
  483. subArgs = append(subArgs, "-vn") // 不输出视频流
  484. subArgs = append(subArgs, "-an") // 不输出音频流
  485. nowCacheFolderPath, err := ffmpegInfo.GetCacheFolderFPath()
  486. if err != nil {
  487. f.log.Errorln("getAudioAndSubExportArgs", videoFileFullPath, err.Error())
  488. return nil, nil
  489. }
  490. if len(ffmpegInfo.SubtitleInfoList) == 0 {
  491. // 如果没有,就返回空
  492. subArgs = nil
  493. } else {
  494. for _, subtitleInfo := range ffmpegInfo.SubtitleInfoList {
  495. f.addSubMapArg(&subArgs, subtitleInfo.Index,
  496. filepath.Join(nowCacheFolderPath, subtitleInfo.GetName()+common.SubExtSRT))
  497. f.addSubMapArg(&subArgs, subtitleInfo.Index,
  498. filepath.Join(nowCacheFolderPath, subtitleInfo.GetName()+common.SubExtASS))
  499. }
  500. }
  501. // 音频导出的参数构建
  502. audioArgs = append(audioArgs, "-vn")
  503. if len(ffmpegInfo.AudioInfoList) == 0 {
  504. // 如果没有,就返回空
  505. audioArgs = nil
  506. } else {
  507. for _, audioInfo := range ffmpegInfo.AudioInfoList {
  508. f.addAudioMapArg(&audioArgs, audioInfo.Index,
  509. filepath.Join(nowCacheFolderPath, audioInfo.GetName()+extPCM))
  510. }
  511. }
  512. return audioArgs, subArgs
  513. }
  514. // getVideoExportArgsByTimeRange 导出某个时间范围内的视频 startTimeString 00:1:27 timeLeng 向后多少秒
  515. func (f *FFMPEGHelper) getVideoExportArgsByTimeRange(videoFullPath string, startTimeString, timeLeng, outVideiFullPath string) []string {
  516. /*
  517. 这个是用 to 到那个时间点
  518. ffmpeg.exe -i '.\Chainsaw Man - S01E02 - ARRIVAL IN TOKYO HDTV-1080p.mp4' -ss 00:00:00 -to 00:05:00 -c:v copy -c:a copy wawa.mp4
  519. 这个是向后多少秒
  520. ffmpeg.exe -i '.\Chainsaw Man - S01E02 - ARRIVAL IN TOKYO HDTV-1080p.mp4' -ss 00:00:00 -t 300 -c:v copy -c:a copy wawa.mp4
  521. */
  522. videoArgs := make([]string, 0)
  523. videoArgs = append(videoArgs, "-ss")
  524. videoArgs = append(videoArgs, startTimeString)
  525. videoArgs = append(videoArgs, "-t")
  526. videoArgs = append(videoArgs, timeLeng)
  527. // 解决开头黑屏问题
  528. videoArgs = append(videoArgs, "-accurate_seek")
  529. videoArgs = append(videoArgs, "-i")
  530. videoArgs = append(videoArgs, videoFullPath)
  531. videoArgs = append(videoArgs, "-c:v")
  532. videoArgs = append(videoArgs, "copy")
  533. videoArgs = append(videoArgs, "-c:a")
  534. videoArgs = append(videoArgs, "copy")
  535. videoArgs = append(videoArgs, outVideiFullPath)
  536. return videoArgs
  537. }
  538. // getVideoHLSExportArgsByTimeRange 导出某个时间范围内的视频的 HLS 信息 startTimeString 00:1:27 timeLeng 向后多少秒
  539. func (f *FFMPEGHelper) getVideoHLSExportArgsByTimeRange(videoFullPath string, startTimeString, timeLeng, sgmentTime, outVideiDirPath string) []string {
  540. /*
  541. ffmpeg.exe -i '111.mp4' -ss 00:00:00 -to 00:05:00 -c:v copy -c:a copy -f segment -segment_time 10 -segment_list outputlist.m3u8 -segment_format mpegts output%03d.ts
  542. */
  543. videoArgs := make([]string, 0)
  544. videoArgs = append(videoArgs, "-ss")
  545. videoArgs = append(videoArgs, startTimeString)
  546. videoArgs = append(videoArgs, "-t")
  547. videoArgs = append(videoArgs, timeLeng)
  548. // 解决开头黑屏问题
  549. videoArgs = append(videoArgs, "-accurate_seek")
  550. videoArgs = append(videoArgs, "-i")
  551. videoArgs = append(videoArgs, videoFullPath)
  552. videoArgs = append(videoArgs, "-force_key_frames")
  553. videoArgs = append(videoArgs, "\"expr:gte(t,n_forced*"+sgmentTime+")\"")
  554. videoArgs = append(videoArgs, "-c:v")
  555. videoArgs = append(videoArgs, "copy")
  556. videoArgs = append(videoArgs, "-c:a")
  557. videoArgs = append(videoArgs, "copy")
  558. videoArgs = append(videoArgs, "-f")
  559. videoArgs = append(videoArgs, "segment")
  560. videoArgs = append(videoArgs, "-segment_time")
  561. videoArgs = append(videoArgs, sgmentTime)
  562. videoArgs = append(videoArgs, "-segment_list")
  563. videoArgs = append(videoArgs, filepath.Join(outVideiDirPath, "outputlist.m3u8"))
  564. videoArgs = append(videoArgs, "-segment_format")
  565. videoArgs = append(videoArgs, "mpegts")
  566. videoArgs = append(videoArgs, filepath.Join(outVideiDirPath, "output%03d.ts"))
  567. return videoArgs
  568. }
  569. func (f *FFMPEGHelper) getVideo2HLSArgs(videoFullPath, segmentTime, outVideoDirPath string) []string {
  570. /*
  571. ffmpeg.exe -i '111.mp4' -c copy -map 0 -f segment -segment_list playlist.m3u8 -segment_time 10 -segment_format mpegts output%03d.ts
  572. */
  573. videoArgs := make([]string, 0)
  574. videoArgs = append(videoArgs, "-i")
  575. videoArgs = append(videoArgs, videoFullPath)
  576. videoArgs = append(videoArgs, "-force_key_frames")
  577. videoArgs = append(videoArgs, "\"expr:gte(t,n_forced*"+segmentTime+")\"")
  578. videoArgs = append(videoArgs, "-c:v")
  579. videoArgs = append(videoArgs, "copy")
  580. videoArgs = append(videoArgs, "-c:a")
  581. videoArgs = append(videoArgs, "copy")
  582. videoArgs = append(videoArgs, "-f")
  583. videoArgs = append(videoArgs, "segment")
  584. videoArgs = append(videoArgs, "-segment_list")
  585. videoArgs = append(videoArgs, filepath.Join(outVideoDirPath, "playlist.m3u8"))
  586. videoArgs = append(videoArgs, "-segment_time")
  587. videoArgs = append(videoArgs, segmentTime)
  588. videoArgs = append(videoArgs, "-segment_format")
  589. videoArgs = append(videoArgs, "mpegts")
  590. videoArgs = append(videoArgs, filepath.Join(outVideoDirPath, "output%03d.ts"))
  591. return videoArgs
  592. }
  593. // getAudioAndSubExportArgsByTimeRange 导出某个时间范围内的音频和字幕文件文件 startTimeString 00:1:27 timeLeng 向后多少秒
  594. func (f *FFMPEGHelper) getAudioExportArgsByTimeRange(audioFullPath string, startTimeString, timeLeng, outAudioFullPath string) []string {
  595. /*
  596. ffmpeg.exe -ar 16000 -ac 1 -f s16le -i aa.pcm -ss 00:1:27 -t 28 -acodec pcm_s16le -f s16le -ac 1 -ar 16000 bb.pcm
  597. ffmpeg.exe -i aa.srt -ss 00:1:27 -t 28 bb.srt
  598. */
  599. var audioArgs = make([]string, 0)
  600. // 指定读取的音频文件编码格式
  601. audioArgs = append(audioArgs, "-ar")
  602. audioArgs = append(audioArgs, "16000")
  603. audioArgs = append(audioArgs, "-ac")
  604. audioArgs = append(audioArgs, "1")
  605. audioArgs = append(audioArgs, "-f")
  606. audioArgs = append(audioArgs, "s16le")
  607. audioArgs = append(audioArgs, "-i")
  608. audioArgs = append(audioArgs, audioFullPath)
  609. audioArgs = append(audioArgs, "-ss")
  610. audioArgs = append(audioArgs, startTimeString)
  611. audioArgs = append(audioArgs, "-t")
  612. audioArgs = append(audioArgs, timeLeng)
  613. // 指定导出的音频文件编码格式
  614. audioArgs = append(audioArgs, "-acodec")
  615. audioArgs = append(audioArgs, "pcm_s16le")
  616. audioArgs = append(audioArgs, "-f")
  617. audioArgs = append(audioArgs, "s16le")
  618. audioArgs = append(audioArgs, "-ac")
  619. audioArgs = append(audioArgs, "1")
  620. audioArgs = append(audioArgs, "-ar")
  621. audioArgs = append(audioArgs, "16000")
  622. audioArgs = append(audioArgs, outAudioFullPath)
  623. return audioArgs
  624. }
  625. func (f *FFMPEGHelper) getSubExportArgsByTimeRange(subFullPath string, startTimeString, timeLength, outSubFullPath string) []string {
  626. /*
  627. ffmpeg.exe -i aa.srt -ss 00:1:27 -t 28 bb.srt
  628. */
  629. var subArgs = make([]string, 0)
  630. subArgs = append(subArgs, "-ss")
  631. subArgs = append(subArgs, startTimeString)
  632. subArgs = append(subArgs, "-t")
  633. subArgs = append(subArgs, timeLength)
  634. subArgs = append(subArgs, "-accurate_seek")
  635. subArgs = append(subArgs, "-i")
  636. subArgs = append(subArgs, subFullPath)
  637. subArgs = append(subArgs, outSubFullPath)
  638. return subArgs
  639. }
  640. // addSubMapArg 构建字幕的导出参数
  641. func (f *FFMPEGHelper) addSubMapArg(subArgs *[]string, index int, subSaveFullPath string) {
  642. *subArgs = append(*subArgs, "-map")
  643. *subArgs = append(*subArgs, fmt.Sprintf("0:%d", index))
  644. *subArgs = append(*subArgs, subSaveFullPath)
  645. }
  646. // addAudioMapArg 构建音频的导出参数
  647. func (f *FFMPEGHelper) addAudioMapArg(subArgs *[]string, index int, audioSaveFullPath string) {
  648. // -acodec pcm_s16le -f s16le -ac 1 -ar 16000
  649. *subArgs = append(*subArgs, "-map")
  650. *subArgs = append(*subArgs, fmt.Sprintf("0:%d", index))
  651. *subArgs = append(*subArgs, "-acodec")
  652. *subArgs = append(*subArgs, "pcm_s16le")
  653. *subArgs = append(*subArgs, "-f")
  654. *subArgs = append(*subArgs, "s16le")
  655. *subArgs = append(*subArgs, "-ac")
  656. *subArgs = append(*subArgs, "1")
  657. *subArgs = append(*subArgs, "-ar")
  658. *subArgs = append(*subArgs, "16000")
  659. *subArgs = append(*subArgs, audioSaveFullPath)
  660. }
  661. func (f *FFMPEGHelper) getVersion(exeName string) (string, error) {
  662. const args = "-version"
  663. cmdArgs := strings.Fields(args)
  664. cmd := exec.Command(exeName, cmdArgs...)
  665. buf := bytes.NewBufferString("")
  666. //指定输出位置
  667. cmd.Stderr = buf
  668. cmd.Stdout = buf
  669. err := cmd.Start()
  670. if err != nil {
  671. return "", err
  672. }
  673. err = cmd.Wait()
  674. if err != nil {
  675. return "", err
  676. }
  677. return buf.String(), nil
  678. }
  679. // isSupportSubCodecName 是否是 FFMPEG 支持的 CodecName
  680. func (f *FFMPEGHelper) isSupportSubCodecName(name string) bool {
  681. switch name {
  682. case Subtitle_StreamCodec_subrip,
  683. Subtitle_StreamCodec_ass,
  684. Subtitle_StreamCodec_ssa,
  685. Subtitle_StreamCodec_srt:
  686. return true
  687. default:
  688. return false
  689. }
  690. }
  691. func (f *FFMPEGHelper) getVideoDuration(videoFileFullPath string) float64 {
  692. const args = "-v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 -i"
  693. cmdArgs := strings.Fields(args)
  694. cmdArgs = append(cmdArgs, videoFileFullPath)
  695. cmd := exec.Command("ffprobe", cmdArgs...)
  696. buf := bytes.NewBufferString("")
  697. //指定输出位置
  698. cmd.Stderr = buf
  699. cmd.Stdout = buf
  700. err := cmd.Start()
  701. if err != nil {
  702. return 0
  703. }
  704. err = cmd.Wait()
  705. if err != nil {
  706. return 0
  707. }
  708. // 字符串转 float64
  709. durationStr := strings.TrimSpace(buf.String())
  710. duration, err := strconv.ParseFloat(durationStr, 32)
  711. if err != nil {
  712. return 0
  713. }
  714. return duration
  715. }
  716. const (
  717. codecTypeSub = "subtitle"
  718. codecTypeAudio = "audio"
  719. extMP3 = ".mp3"
  720. extPCM = ".pcm"
  721. )
  722. type ExportType int
  723. const (
  724. Subtitle ExportType = iota // 导出字幕
  725. Audio // 导出音频
  726. SubtitleAndAudio // 导出字幕和音频
  727. )
  728. /*
  729. FFMPEG 支持的字幕 Codec Name:
  730. ..S... arib_caption ARIB STD-B24 caption
  731. DES... ass ASS (Advanced SSA) subtitle (decoders: ssa ass ) (encoders: ssa ass )
  732. DES... dvb_subtitle DVB subtitles (decoders: dvbsub ) (encoders: dvbsub )
  733. ..S... dvb_teletext DVB teletext
  734. DES... dvd_subtitle DVD subtitles (decoders: dvdsub ) (encoders: dvdsub )
  735. D.S... eia_608 EIA-608 closed captions (decoders: cc_dec )
  736. D.S... hdmv_pgs_subtitle HDMV Presentation Graphic Stream subtitles (decoders: pgssub )
  737. ..S... hdmv_text_subtitle HDMV Text subtitle
  738. D.S... jacosub JACOsub subtitle
  739. D.S... microdvd MicroDVD subtitle
  740. DES... mov_text MOV text
  741. D.S... mpl2 MPL2 subtitle
  742. D.S... pjs PJS (Phoenix Japanimation Society) subtitle
  743. D.S... realtext RealText subtitle
  744. D.S... sami SAMI subtitle
  745. ..S... srt SubRip subtitle with embedded timing
  746. ..S... ssa SSA (SubStation Alpha) subtitle
  747. D.S... stl Spruce subtitle format
  748. DES... subrip SubRip subtitle (decoders: srt subrip ) (encoders: srt subrip )
  749. D.S... subviewer SubViewer subtitle
  750. D.S... subviewer1 SubViewer v1 subtitle
  751. DES... text raw UTF-8 text
  752. ..S... ttml Timed Text Markup Language
  753. D.S... vplayer VPlayer subtitle
  754. DES... webvtt WebVTT subtitle
  755. DES... xsub XSUB
  756. */
  757. const (
  758. Subtitle_StreamCodec_subrip = "subrip"
  759. Subtitle_StreamCodec_ass = "ass"
  760. Subtitle_StreamCodec_ssa = "ssa"
  761. Subtitle_StreamCodec_srt = "srt"
  762. )