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