]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - scripts/optimize-old-videos.ts
Don't expose constants directly in initializers/
[github/Chocobozzz/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 for (const file of video.VideoFiles) {
36 currentFile = join(CONFIG.STORAGE.VIDEOS_DIR, video.getVideoFilename(file))
37
38 const [ videoBitrate, fps, resolution ] = await Promise.all([
39 getVideoFileBitrate(currentFile),
40 getVideoFileFPS(currentFile),
41 getVideoFileResolution(currentFile)
42 ])
43
44 const maxBitrate = getMaxBitrate(resolution.videoFileResolution, fps, VIDEO_TRANSCODING_FPS)
45 const isMaxBitrateExceeded = videoBitrate > maxBitrate
46 if (isMaxBitrateExceeded) {
47 console.log('Optimizing video file %s with bitrate %s kbps (max: %s kbps)',
48 basename(currentFile), videoBitrate / 1000, maxBitrate / 1000)
49 const backupFile = `${currentFile}_backup`
50 await copy(currentFile, backupFile)
51 await optimizeVideofile(video, file)
52 const originalDuration = await getDurationFromVideoFile(backupFile)
53 const newDuration = await getDurationFromVideoFile(currentFile)
54 if (originalDuration === newDuration) {
55 console.log('Finished optimizing %s', basename(currentFile))
56 await remove(backupFile)
57 } else {
58 console.log('Failed to optimize %s, restoring original', basename(currentFile))
59 move(backupFile, currentFile, { overwrite: true })
60 await video.createTorrentAndSetInfoHash(file)
61 await file.save()
62 }
63 }
64 }
65 }
66
67 console.log('Finished optimizing videos')
68 }