2
1

optimize-old-videos.ts 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import { VIDEO_TRANSCODING_FPS } from '../server/initializers/constants'
  2. import { getDurationFromVideoFile, getVideoFileBitrate, getVideoFileFPS, getVideoFileResolution } from '../server/helpers/ffmpeg-utils'
  3. import { getMaxBitrate } from '../shared/models/videos'
  4. import { VideoModel } from '../server/models/video/video'
  5. import { optimizeVideofile } from '../server/lib/video-transcoding'
  6. import { initDatabaseModels } from '../server/initializers'
  7. import { basename, dirname, join } from 'path'
  8. import { copy, move, remove } from 'fs-extra'
  9. import { CONFIG } from '../server/initializers/config'
  10. run()
  11. .then(() => process.exit(0))
  12. .catch(err => {
  13. console.error(err)
  14. process.exit(-1)
  15. })
  16. let currentVideoId = null
  17. let currentFile = null
  18. process.on('SIGINT', async function () {
  19. console.log('Cleaning up temp files')
  20. await remove(`${currentFile}_backup`)
  21. await remove(`${dirname(currentFile)}/${currentVideoId}-transcoded.mp4`)
  22. process.exit(0)
  23. })
  24. async function run () {
  25. await initDatabaseModels(true)
  26. const localVideos = await VideoModel.listLocal()
  27. for (const video of localVideos) {
  28. currentVideoId = video.id
  29. for (const file of video.VideoFiles) {
  30. currentFile = join(CONFIG.STORAGE.VIDEOS_DIR, video.getVideoFilename(file))
  31. const [ videoBitrate, fps, resolution ] = await Promise.all([
  32. getVideoFileBitrate(currentFile),
  33. getVideoFileFPS(currentFile),
  34. getVideoFileResolution(currentFile)
  35. ])
  36. const maxBitrate = getMaxBitrate(resolution.videoFileResolution, fps, VIDEO_TRANSCODING_FPS)
  37. const isMaxBitrateExceeded = videoBitrate > maxBitrate
  38. if (isMaxBitrateExceeded) {
  39. console.log(
  40. 'Optimizing video file %s with bitrate %s kbps (max: %s kbps)',
  41. basename(currentFile), videoBitrate / 1000, maxBitrate / 1000
  42. )
  43. const backupFile = `${currentFile}_backup`
  44. await copy(currentFile, backupFile)
  45. await optimizeVideofile(video, file)
  46. const originalDuration = await getDurationFromVideoFile(backupFile)
  47. const newDuration = await getDurationFromVideoFile(currentFile)
  48. if (originalDuration === newDuration) {
  49. console.log('Finished optimizing %s', basename(currentFile))
  50. await remove(backupFile)
  51. continue
  52. }
  53. console.log('Failed to optimize %s, restoring original', basename(currentFile))
  54. await move(backupFile, currentFile, { overwrite: true })
  55. await video.createTorrentAndSetInfoHash(file)
  56. await file.save()
  57. }
  58. }
  59. }
  60. console.log('Finished optimizing videos')
  61. }