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 { optimizeOriginalVideofile } from '../server/lib/video-transcoding'
9 import { initDatabaseModels } from '../server/initializers'
10 import { basename, dirname } from 'path'
11 import { copy, move, remove } from 'fs-extra'
12 import { createTorrentAndSetInfoHash } from '@server/helpers/webtorrent'
13 import { getVideoFilePath } from '@server/lib/video-paths'
16 .then(() => process.exit(0))
22 let currentVideoId = null
23 let currentFile = null
25 process.on('SIGINT', async function () {
26 console.log('Cleaning up temp files')
27 await remove(`${currentFile}_backup`)
28 await remove(`${dirname(currentFile)}/${currentVideoId}-transcoded.mp4`)
32 async function run () {
33 await initDatabaseModels(true)
35 const localVideos = await VideoModel.listLocal()
37 for (const video of localVideos) {
38 currentVideoId = video.id
40 for (const file of video.VideoFiles) {
41 currentFile = getVideoFilePath(video, file)
43 const [ videoBitrate, fps, resolution ] = await Promise.all([
44 getVideoFileBitrate(currentFile),
45 getVideoFileFPS(currentFile),
46 getVideoFileResolution(currentFile)
49 const maxBitrate = getMaxBitrate(resolution.videoFileResolution, fps, VIDEO_TRANSCODING_FPS)
50 const isMaxBitrateExceeded = videoBitrate > maxBitrate
51 if (isMaxBitrateExceeded) {
53 'Optimizing video file %s with bitrate %s kbps (max: %s kbps)',
54 basename(currentFile), videoBitrate / 1000, maxBitrate / 1000
57 const backupFile = `${currentFile}_backup`
58 await copy(currentFile, backupFile)
60 await optimizeOriginalVideofile(video, file)
62 const originalDuration = await getDurationFromVideoFile(backupFile)
63 const newDuration = await getDurationFromVideoFile(currentFile)
65 if (originalDuration === newDuration) {
66 console.log('Finished optimizing %s', basename(currentFile))
67 await remove(backupFile)
71 console.log('Failed to optimize %s, restoring original', basename(currentFile))
72 await move(backupFile, currentFile, { overwrite: true })
73 await createTorrentAndSetInfoHash(video, file)
79 console.log('Finished optimizing videos')