0b0e6037e4da688575e360f8122a2a195a8b71ad
[oweals/peertube.git] / scripts / optimize-old-videos.ts
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
11 run()
12   .then(() => process.exit(0))
13   .catch(err => {
14     console.error(err)
15     process.exit(-1)
16   })
17
18 let currentVideoId = null
19 let currentFile = null
20
21 process.on('SIGINT', async function () {
22   console.log('Cleaning up temp files')
23   await remove(`${currentFile}_backup`)
24   await remove(`${dirname(currentFile)}/${currentVideoId}-transcoded.mp4`)
25   process.exit(0)
26 })
27
28 async function run () {
29   await initDatabaseModels(true)
30
31   const localVideos = await VideoModel.listLocal()
32
33   for (const video of localVideos) {
34     currentVideoId = video.id
35
36     for (const file of video.VideoFiles) {
37       currentFile = join(CONFIG.STORAGE.VIDEOS_DIR, video.getVideoFilename(file))
38
39       const [ videoBitrate, fps, resolution ] = await Promise.all([
40         getVideoFileBitrate(currentFile),
41         getVideoFileFPS(currentFile),
42         getVideoFileResolution(currentFile)
43       ])
44
45       const maxBitrate = getMaxBitrate(resolution.videoFileResolution, fps, VIDEO_TRANSCODING_FPS)
46       const isMaxBitrateExceeded = videoBitrate > maxBitrate
47       if (isMaxBitrateExceeded) {
48         console.log(
49           'Optimizing video file %s with bitrate %s kbps (max: %s kbps)',
50           basename(currentFile), videoBitrate / 1000, maxBitrate / 1000
51         )
52
53         const backupFile = `${currentFile}_backup`
54         await copy(currentFile, backupFile)
55
56         await optimizeVideofile(video, file)
57
58         const originalDuration = await getDurationFromVideoFile(backupFile)
59         const newDuration = await getDurationFromVideoFile(currentFile)
60
61         if (originalDuration === newDuration) {
62           console.log('Finished optimizing %s', basename(currentFile))
63           await remove(backupFile)
64           continue
65         }
66
67         console.log('Failed to optimize %s, restoring original', basename(currentFile))
68         await move(backupFile, currentFile, { overwrite: true })
69         await video.createTorrentAndSetInfoHash(file)
70         await file.save()
71       }
72     }
73   }
74
75   console.log('Finished optimizing videos')
76 }