video-tools.test.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  1. import { describe, expect, it } from 'vitest'
  2. import {
  3. buildFfmpegArgs,
  4. colorsMatch,
  5. cutRangesProblem,
  6. sourceTimeAt,
  7. encoderArgs,
  8. outputDuration,
  9. outputExtension,
  10. parseFrameColor,
  11. DEFAULT_VIDEO_SETTINGS,
  12. normalizeVideoSettings,
  13. planQuickOptimize,
  14. parseProgressSeconds,
  15. pickEncoder,
  16. scaleFilter,
  17. fpsFilter,
  18. normalizeFps,
  19. targetSize,
  20. type VideoInfo
  21. } from './video-tools'
  22. const info: VideoInfo = { codec: 'h264', width: 3840, height: 2160, fps: 30, duration: 60, size: 1000, bitDepth: 8, hasAudio: true }
  23. describe('targetSize', () => {
  24. it('fits a 16:9 video into a 1080p box', () => {
  25. expect(targetSize(info, { width: 1920, height: 1080 }, 'fit')).toEqual({ width: 1920, height: 1080 })
  26. })
  27. it('keeps the aspect of a non-16:9 video inside an ultrawide box', () => {
  28. expect(targetSize({ width: 3840, height: 2160 }, { width: 3440, height: 1440 }, 'fit')).toEqual({ width: 2560, height: 1440 })
  29. })
  30. it('fits a 4:3 video into a portrait box', () => {
  31. expect(targetSize({ width: 2048, height: 1536 }, { width: 1080, height: 2400 }, 'fit')).toEqual({ width: 1080, height: 810 })
  32. })
  33. it('rounds to even numbers', () => {
  34. const size = targetSize({ width: 1001, height: 563 }, { width: 500, height: 500 }, 'fit')!
  35. expect(size.width % 2).toBe(0)
  36. expect(size.height % 2).toBe(0)
  37. })
  38. it('never upscales', () => {
  39. expect(targetSize({ width: 1280, height: 720 }, { width: 1920, height: 1080 }, 'fit')).toBeNull()
  40. expect(targetSize({ width: 1920, height: 1080 }, { width: 1920, height: 1080 }, 'fit')).toBeNull()
  41. })
  42. it('fill covers the box exactly and crops', () => {
  43. expect(targetSize({ width: 3840, height: 2160 }, { width: 3440, height: 1440 }, 'fill')).toEqual({ width: 3440, height: 1440 })
  44. })
  45. it('fill refuses when one side would have to grow', () => {
  46. expect(targetSize({ width: 3840, height: 1000 }, { width: 1920, height: 1080 }, 'fill')).toBeNull()
  47. })
  48. it('rejects nonsense sizes', () => {
  49. expect(targetSize({ width: 0, height: 0 }, { width: 100, height: 100 }, 'fit')).toBeNull()
  50. expect(targetSize(info, { width: 0, height: 100 }, 'fit')).toBeNull()
  51. })
  52. })
  53. describe('scaleFilter', () => {
  54. it('scales for fit', () => {
  55. expect(scaleFilter(info, { width: 1920, height: 1080 }, 'fit')).toBe('scale=1920:1080:flags=lanczos')
  56. })
  57. it('scales up to cover, then crops, for fill', () => {
  58. expect(scaleFilter(info, { width: 3440, height: 1440 }, 'fill')).toBe(
  59. 'scale=3440:1440:force_original_aspect_ratio=increase:flags=lanczos,crop=3440:1440'
  60. )
  61. })
  62. it('is null when nothing would shrink', () => {
  63. expect(scaleFilter(info, { width: 7680, height: 4320 }, 'fit')).toBeNull()
  64. })
  65. })
  66. describe('pickEncoder', () => {
  67. const all = [
  68. { encoder: 'libx265' as const, source: 'system' as const },
  69. { encoder: 'hevc_vaapi' as const, source: 'system' as const },
  70. { encoder: 'hevc_nvenc' as const, source: 'downloaded' as const }
  71. ]
  72. it('auto takes the fastest one', () => {
  73. expect(pickEncoder('auto', all)?.encoder).toBe('hevc_nvenc')
  74. expect(pickEncoder('auto', all.slice(0, 2))?.encoder).toBe('hevc_vaapi')
  75. expect(pickEncoder('auto', all.slice(0, 1))?.encoder).toBe('libx265')
  76. })
  77. it('takes the named one, or nothing when it does not work here', () => {
  78. expect(pickEncoder('libx265', all)?.encoder).toBe('libx265')
  79. expect(pickEncoder('hevc_amf', all)).toBeUndefined()
  80. expect(pickEncoder('auto', [])).toBeUndefined()
  81. })
  82. })
  83. describe('outputExtension', () => {
  84. it('keeps containers that hold HEVC and moves the others to mkv', () => {
  85. expect(outputExtension('.MP4')).toBe('.MP4')
  86. expect(outputExtension('.WEBM')).toBe('.mkv')
  87. expect(outputExtension('.mov')).toBe('.mov')
  88. expect(outputExtension('.webm')).toBe('.mkv')
  89. expect(outputExtension('.avi')).toBe('.mkv')
  90. })
  91. })
  92. describe('fps cap', () => {
  93. it('accepts whole numbers only', () => {
  94. expect(normalizeFps(45)).toBe(45)
  95. expect(normalizeFps(0)).toBe(0)
  96. expect(normalizeFps(12.5)).toBe(0)
  97. expect(normalizeFps(999)).toBe(0)
  98. expect(normalizeFps('30')).toBe(0)
  99. })
  100. it('only filters a clearly higher rate', () => {
  101. expect(fpsFilter({ fps: 60 }, 30)).toBe('fps=30')
  102. expect(fpsFilter({ fps: 30 }, 30)).toBeNull()
  103. expect(fpsFilter({ fps: 30 }, undefined)).toBeNull()
  104. })
  105. it('puts fps before the scale filter', () => {
  106. const args = buildFfmpegArgs({
  107. source: 'in.mp4', dest: 'out.mp4', info: { ...info, fps: 60 },
  108. options: { encoder: 'libx265', fps: 30, scale: { width: 1920, height: 1080, mode: 'fit' } }, encoder: 'libx265'
  109. })
  110. expect(args[args.indexOf('-vf') + 1]).toMatch(/^fps=30,scale=/)
  111. })
  112. })
  113. describe('buildFfmpegArgs', () => {
  114. it('re-encodes with libx265 and tags mp4 as hvc1', () => {
  115. const args = buildFfmpegArgs({ source: 'in.mp4', dest: 'out.mp4', info, options: { encoder: 'auto' }, encoder: 'libx265' })
  116. expect(args).toContain('libx265')
  117. expect(args.join(' ')).toContain('-tag:v hvc1')
  118. expect(args.join(' ')).toContain('-c:a copy')
  119. expect(args.join(' ')).toContain('-movflags +faststart')
  120. expect(args.at(-1)).toBe('out.mp4')
  121. expect(args).not.toContain('-vf')
  122. })
  123. it('re-encodes the sound of a cut, copied audio starts at the keyframe before it and moves the video', () => {
  124. const cut = buildFfmpegArgs({
  125. source: 'in.mp4', dest: 'out.mp4', info,
  126. options: { encoder: 'auto', cut: { start: 960, end: 1500 } }, encoder: 'libx265'
  127. }).join(' ')
  128. expect(cut).toContain('-c:a aac')
  129. expect(cut).not.toContain('-c:a copy')
  130. const fast = buildFfmpegArgs({
  131. source: 'in.mp4', dest: 'out.mp4', info,
  132. options: { encoder: 'auto', cut: { start: 960, end: 1500, copy: true } }
  133. }).join(' ')
  134. expect(fast).toContain('-c:a copy')
  135. })
  136. it('does not tag a VAAPI mp4 as hvc1, the encoder keeps its parameter sets in the stream', () => {
  137. const args = buildFfmpegArgs({ source: 'in.mp4', dest: 'out.mp4', info, options: { encoder: 'auto' }, encoder: 'hevc_vaapi' })
  138. expect(args).toContain('hevc_vaapi')
  139. expect(args.join(' ')).not.toContain('hvc1')
  140. const nvenc = buildFfmpegArgs({ source: 'in.mp4', dest: 'out.mp4', info, options: { encoder: 'auto' }, encoder: 'hevc_nvenc' })
  141. expect(nvenc.join(' ')).toContain('-tag:v hvc1')
  142. })
  143. it('puts the scale filter before the vaapi upload', () => {
  144. const args = buildFfmpegArgs({
  145. source: 'in.mp4', dest: 'out.mp4', info,
  146. options: { encoder: 'hevc_vaapi', scale: { width: 1920, height: 1080, mode: 'fit' } },
  147. encoder: 'hevc_vaapi', vaapiDevice: '/dev/dri/renderD129'
  148. })
  149. expect(args.slice(args.indexOf('-vaapi_device'), args.indexOf('-vaapi_device') + 2)).toEqual(['-vaapi_device', '/dev/dri/renderD129'])
  150. expect(args[args.indexOf('-vf') + 1]).toBe('scale=1920:1080:flags=lanczos,format=nv12,hwupload')
  151. expect(args.indexOf('-vaapi_device')).toBeLessThan(args.indexOf('-i'))
  152. })
  153. it('seeks in the input when re-encoding, which is frame exact and skips the decoding before the cut', () => {
  154. const args = buildFfmpegArgs({
  155. source: 'in.mp4', dest: 'out.mp4', info, options: { encoder: 'auto', cut: { start: 2, end: 10 } }, encoder: 'libx265'
  156. })
  157. expect(args.indexOf('-ss')).toBeLessThan(args.indexOf('-i'))
  158. expect(args.indexOf('-to')).toBeLessThan(args.indexOf('-i'))
  159. })
  160. it('copies the streams for a fast cut', () => {
  161. const args = buildFfmpegArgs({
  162. source: 'in.mp4', dest: 'out.mp4', info, options: { encoder: 'auto', cut: { start: 2, end: 10, copy: true } }
  163. })
  164. expect(args.indexOf('-ss')).toBeLessThan(args.indexOf('-i'))
  165. expect(args.join(' ')).toContain('-c:v copy')
  166. })
  167. it('keeps 10 bit sources at 10 bit', () => {
  168. const args = buildFfmpegArgs({ source: 'in.mkv', dest: 'out.mkv', info: { ...info, bitDepth: 10 }, options: { encoder: 'auto' }, encoder: 'libx265' })
  169. expect(args).toContain('yuv420p10le')
  170. expect(args.join(' ')).not.toContain('hvc1')
  171. })
  172. })
  173. describe('progress and cut length', () => {
  174. it('reads the last out_time of a chunk', () => {
  175. expect(parseProgressSeconds('frame=10\nout_time_us=1500000\nprogress=continue\nout_time_us=2500000\n')).toBe(2.5)
  176. expect(parseProgressSeconds('frame=10\n')).toBeUndefined()
  177. })
  178. it('counts the cut length', () => {
  179. expect(outputDuration(info)).toBe(60)
  180. expect(outputDuration(info, { start: 10, end: 25 })).toBe(15)
  181. expect(outputDuration(info, { start: 10, end: 500 })).toBe(50)
  182. })
  183. })
  184. describe('picture check', () => {
  185. const stats = (y: number, u: number, v: number): string =>
  186. `lavfi.signalstats.YAVG=${y}\nlavfi.signalstats.UAVG=${u}\nlavfi.signalstats.VAVG=${v}\nlavfi.signalstats.SATAVG=95`
  187. it('reads the averages of the first frame', () => {
  188. expect(parseFrameColor(stats(124.8, 127.1, 125.1))).toEqual({ y: 124.8, u: 127.1, v: 125.1 })
  189. expect(parseFrameColor('nothing here')).toBeNull()
  190. })
  191. it('accepts a faithful encode and rejects a green one', () => {
  192. const source = parseFrameColor(stats(125, 127, 125))!
  193. expect(colorsMatch(source, parseFrameColor(stats(124, 128, 126))!)).toBe(true)
  194. expect(colorsMatch(source, parseFrameColor(stats(145, 55, 35))!)).toBe(false)
  195. })
  196. })
  197. describe('quality', () => {
  198. it('uses the CRF for libx265, two higher for the GPU encoders, and keeps it in 22 to 31', () => {
  199. expect(encoderArgs('libx265', 8).output).toContain('26')
  200. expect(encoderArgs('libx265', 8, undefined, 31).output).toContain('31')
  201. expect(encoderArgs('libx265', 8, undefined, 10).output).toContain('22')
  202. expect(encoderArgs('libx265', 8, undefined, 99).output).toContain('31')
  203. expect(encoderArgs('hevc_vaapi', 8, '/dev/dri/renderD128', 22).output).toContain('24')
  204. expect(encoderArgs('hevc_nvenc', 8, undefined, 31).output).toContain('33')
  205. })
  206. })
  207. describe('quick optimize plan', () => {
  208. const hd: VideoInfo = { ...info, codec: 'h264', width: 1920, height: 1080 }
  209. const uhd: VideoInfo = { ...info, codec: 'h264', width: 3840, height: 2160 }
  210. const withScale = (scaleTo: 'none' | '4k' | '1440p' | '1080p' | '720p') => ({ ...DEFAULT_VIDEO_SETTINGS, scaleTo })
  211. it('converts a non-HEVC video with the default settings and keeps its size', () => {
  212. const plan = planQuickOptimize(hd, DEFAULT_VIDEO_SETTINGS)
  213. expect(plan).toEqual({ options: { encoder: 'auto', crf: 26 } })
  214. })
  215. it('never enlarges: a 1080p video stays 1080p even with a 4K target', () => {
  216. const plan = planQuickOptimize(hd, withScale('4k'))
  217. expect(plan).toEqual({ options: { encoder: 'auto', crf: 26 } })
  218. expect('options' in plan && plan.options.scale).toBeFalsy()
  219. })
  220. it('cuts to the trim, also on a video that is already H.265', () => {
  221. const cut = { start: 5, end: 20 }
  222. expect(planQuickOptimize(hd, DEFAULT_VIDEO_SETTINGS, cut)).toEqual({ options: { encoder: 'auto', crf: 26, cut } })
  223. const plan = planQuickOptimize({ ...hd, codec: 'hevc' }, DEFAULT_VIDEO_SETTINGS, cut)
  224. expect('options' in plan && plan.options.cut).toEqual(cut)
  225. })
  226. it('reads the trim mode and falls back to asking', () => {
  227. expect(normalizeVideoSettings({ trimMode: 'auto' }).trimMode).toBe('auto')
  228. expect(normalizeVideoSettings({ trimMode: 'sometimes' }).trimMode).toBe('ask')
  229. expect(normalizeVideoSettings(undefined).trimMode).toBe('ask')
  230. })
  231. it('scales a larger video down to the target', () => {
  232. const plan = planQuickOptimize(uhd, withScale('1080p'))
  233. expect('options' in plan && plan.options.scale).toEqual({ width: 1920, height: 1080, mode: 'fit' })
  234. })
  235. it('leaves an H.265 video alone unless it can be scaled down', () => {
  236. expect(planQuickOptimize({ ...hd, codec: 'hevc' }, DEFAULT_VIDEO_SETTINGS)).toEqual({ skip: 'hevc' })
  237. expect(planQuickOptimize({ ...hd, codec: 'hevc' }, withScale('1080p'))).toEqual({ skip: 'hevcSize', size: '1080p' })
  238. const plan = planQuickOptimize({ ...uhd, codec: 'hevc' }, withScale('1440p'))
  239. expect('options' in plan && plan.options.scale?.height).toBe(1440)
  240. })
  241. it('cleans up stored settings', () => {
  242. expect(normalizeVideoSettings(undefined)).toEqual(DEFAULT_VIDEO_SETTINGS)
  243. expect(normalizeVideoSettings({ backupOriginal: false, encoder: 'nope', crf: 99, scaleTo: '8k', scaleMode: 'fill' })).toEqual({
  244. backupOriginal: false,
  245. encoder: 'auto',
  246. crf: 31,
  247. scaleTo: 'none',
  248. scaleMode: 'fill',
  249. maxFps: 0,
  250. trimMode: 'ask'
  251. })
  252. })
  253. })
  254. describe('hardware decoding', () => {
  255. it('asks ffmpeg for the machine\'s own decoder in front of every input', () => {
  256. const one = buildFfmpegArgs({ source: 'in.mp4', dest: 'out.mp4', info, options: { encoder: 'auto' }, encoder: 'hevc_nvenc', hwDecode: true })
  257. expect(one.join(' ')).toContain('-hwaccel auto -i in.mp4')
  258. const cut = { start: 0, end: 10, more: [{ start: 20, end: 30 }] }
  259. const two = buildFfmpegArgs({ source: 'in.mp4', dest: 'out.mp4', info, options: { encoder: 'auto', cut }, encoder: 'libx265', hwDecode: true })
  260. expect(two.filter((a) => a === '-hwaccel')).toHaveLength(2)
  261. })
  262. it('stays off without the flag and when only copying', () => {
  263. expect(buildFfmpegArgs({ source: 'in.mp4', dest: 'out.mp4', info, options: { encoder: 'auto' }, encoder: 'libx265' })).not.toContain('-hwaccel')
  264. expect(buildFfmpegArgs({ source: 'in.mp4', dest: 'out.mp4', info, options: { encoder: 'auto', cut: { start: 1, end: 5, copy: true } }, hwDecode: true })).not.toContain('-hwaccel')
  265. })
  266. })
  267. describe('cutting several parts together', () => {
  268. const cut = { start: 0, end: 60, more: [{ start: 180, end: 240 }] }
  269. const long: VideoInfo = { ...info, duration: 300 }
  270. it('joins the parts with trim and concat instead of seeking', () => {
  271. const args = buildFfmpegArgs({ source: 'in.mp4', dest: 'out.mp4', info: long, options: { encoder: 'auto', cut }, encoder: 'libx265' })
  272. const graph = args[args.indexOf('-filter_complex') + 1]
  273. expect(args.join(' ')).toContain('-ss 0 -to 60 -i in.mp4 -ss 180 -to 240 -i in.mp4')
  274. expect(graph).toContain('[0:v:0]setpts=PTS-STARTPTS[v0]')
  275. expect(graph).toContain('[1:a:0]asetpts=PTS-STARTPTS[a1]')
  276. expect(graph).toContain('[v0][a0][v1][a1]concat=n=2:v=1:a=1[vj][aj]')
  277. expect(graph).toContain('[vj]null[vout]')
  278. expect(args).toContain('[aj]')
  279. expect(args.join(' ')).toContain('-c:a aac')
  280. })
  281. it('runs scale and frame rate after the join and leaves out audio filters for a silent video', () => {
  282. const args = buildFfmpegArgs({
  283. source: 'in.mp4', dest: 'out.mkv', info: { ...long, hasAudio: false },
  284. options: { encoder: 'auto', cut, fps: 24, scale: { width: 1920, height: 1080, mode: 'fit' } }, encoder: 'hevc_vaapi'
  285. })
  286. const graph = args[args.indexOf('-filter_complex') + 1]
  287. expect(graph).not.toContain('asetpts')
  288. expect(graph).toContain('[v0][v1]concat=n=2:v=1:a=0[vj]')
  289. expect(graph).toContain('[vj]fps=24,scale=1920:1080:flags=lanczos,format=nv12,hwupload[vout]')
  290. expect(args).not.toContain('-vf')
  291. })
  292. it('cannot be joined by copying', () => {
  293. expect(() => buildFfmpegArgs({ source: 'in.mp4', dest: 'out.mp4', info: long, options: { encoder: 'auto', cut } })).toThrow('needs an encoder')
  294. })
  295. it('adds the lengths of all parts', () => {
  296. expect(outputDuration(long, cut)).toBe(120)
  297. expect(outputDuration(long, { start: 0, end: 60, more: [{ start: 280, end: 900 }] })).toBe(80)
  298. })
  299. it('maps a time of the result back into the source', () => {
  300. expect(sourceTimeAt(cut, 10, 300)).toBe(10)
  301. expect(sourceTimeAt(cut, 70, 300)).toBe(190)
  302. expect(sourceTimeAt(cut, 500, 300)).toBe(240)
  303. expect(sourceTimeAt(undefined, 7, 300)).toBe(7)
  304. })
  305. it('rejects parts outside the video or out of order', () => {
  306. expect(cutRangesProblem([{ start: 0, end: 60 }, { start: 180, end: 240 }], 300)).toBeNull()
  307. expect(cutRangesProblem([{ start: 0, end: 60 }, { start: 50, end: 240 }], 300)).toBe('order')
  308. expect(cutRangesProblem([{ start: 200, end: 100 }], 300)).toBe('range')
  309. expect(cutRangesProblem([{ start: 0, end: 60 }, { start: 400, end: 500 }], 300)).toBe('range')
  310. expect(cutRangesProblem([], 300)).toBe('range')
  311. })
  312. })