aboutsummaryrefslogtreecommitdiffhomepage
path: root/scripts/optimize-old-videos.ts
diff options
context:
space:
mode:
Diffstat (limited to 'scripts/optimize-old-videos.ts')
-rw-r--r--scripts/optimize-old-videos.ts67
1 files changed, 67 insertions, 0 deletions
diff --git a/scripts/optimize-old-videos.ts b/scripts/optimize-old-videos.ts
new file mode 100644
index 000000000..1bee1b0f3
--- /dev/null
+++ b/scripts/optimize-old-videos.ts
@@ -0,0 +1,67 @@
1import { CONFIG, VIDEO_TRANSCODING_FPS } from '../server/initializers/constants'
2import { getVideoFileBitrate, getVideoFileFPS, getVideoFileResolution, getDurationFromVideoFile } from '../server/helpers/ffmpeg-utils'
3import { getMaxBitrate } from '../shared/models/videos'
4import { VideoModel } from '../server/models/video/video'
5import { optimizeVideofile } from '../server/lib/video-transcoding'
6import { initDatabaseModels } from '../server/initializers'
7import { join, basename, dirname } from 'path'
8import { copy, remove, move } from 'fs-extra'
9
10run()
11 .then(() => process.exit(0))
12 .catch(err => {
13 console.error(err)
14 process.exit(-1)
15 })
16
17let currentVideoId = null
18let currentFile = null
19
20process.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
27async 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}