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