optimize-old-videos.ts 2.5 KB

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