1 import { registerTSPaths } from '../server/helpers/register-ts-paths'
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'
15 .then(() => process.exit(0))
21 let currentVideoId = null
22 let currentFile = null
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`)
31 async function run () {
32 await initDatabaseModels(true)
34 const localVideos = await VideoModel.listLocal()
36 for (const video of localVideos) {
37 currentVideoId = video.id
39 for (const file of video.VideoFiles) {
40 currentFile = join(CONFIG.STORAGE.VIDEOS_DIR, video.getVideoFilename(file))
42 const [ videoBitrate, fps, resolution ] = await Promise.all([
43 getVideoFileBitrate(currentFile),
44 getVideoFileFPS(currentFile),
45 getVideoFileResolution(currentFile)
48 const maxBitrate = getMaxBitrate(resolution.videoFileResolution, fps, VIDEO_TRANSCODING_FPS)
49 const isMaxBitrateExceeded = videoBitrate > maxBitrate
50 if (isMaxBitrateExceeded) {
52 'Optimizing video file %s with bitrate %s kbps (max: %s kbps)',
53 basename(currentFile), videoBitrate / 1000, maxBitrate / 1000
56 const backupFile = `${currentFile}_backup`
57 await copy(currentFile, backupFile)
59 await optimizeVideofile(video, file)
61 const originalDuration = await getDurationFromVideoFile(backupFile)
62 const newDuration = await getDurationFromVideoFile(currentFile)
64 if (originalDuration === newDuration) {
65 console.log('Finished optimizing %s', basename(currentFile))
66 await remove(backupFile)
70 console.log('Failed to optimize %s, restoring original', basename(currentFile))
71 await move(backupFile, currentFile, { overwrite: true })
72 await video.createTorrentAndSetInfoHash(file)
78 console.log('Finished optimizing videos')