1 import { registerTSPaths } from '../server/helpers/register-ts-paths'
4 import { getDurationFromVideoFile, getVideoFileBitrate, getVideoFileFPS, getVideoFileResolution } from '../server/helpers/ffprobe-utils'
5 import { VideoModel } from '../server/models/video/video'
6 import { optimizeOriginalVideofile } from '../server/lib/transcoding/video-transcoding'
7 import { initDatabaseModels } from '../server/initializers/database'
8 import { basename, dirname } from 'path'
9 import { copy, move, remove } from 'fs-extra'
10 import { createTorrentAndSetInfoHash } from '@server/helpers/webtorrent'
11 import { getVideoFilePath } from '@server/lib/video-paths'
12 import { getMaxBitrate } from '@shared/core-utils'
15 .then(() => process.exit(0))
21 let currentVideoId: string
22 let currentFilePath: string
24 process.on('SIGINT', async function () {
25 console.log('Cleaning up temp files')
26 await remove(`${currentFilePath}_backup`)
27 await remove(`${dirname(currentFilePath)}/${currentVideoId}-transcoded.mp4`)
31 async function run () {
32 await initDatabaseModels(true)
34 const localVideos = await VideoModel.listLocal()
36 for (const localVideo of localVideos) {
37 const video = await VideoModel.loadAndPopulateAccountAndServerAndTags(localVideo.id)
39 currentVideoId = video.id
41 for (const file of video.VideoFiles) {
42 currentFilePath = getVideoFilePath(video, file)
44 const [ videoBitrate, fps, dataResolution ] = await Promise.all([
45 getVideoFileBitrate(currentFilePath),
46 getVideoFileFPS(currentFilePath),
47 getVideoFileResolution(currentFilePath)
50 const maxBitrate = getMaxBitrate({ ...dataResolution, fps })
51 const isMaxBitrateExceeded = videoBitrate > maxBitrate
52 if (isMaxBitrateExceeded) {
54 'Optimizing video file %s with bitrate %s kbps (max: %s kbps)',
55 basename(currentFilePath), videoBitrate / 1000, maxBitrate / 1000
58 const backupFile = `${currentFilePath}_backup`
59 await copy(currentFilePath, backupFile)
61 await optimizeOriginalVideofile(video, file)
62 // Update file path, the video filename changed
63 currentFilePath = getVideoFilePath(video, file)
65 const originalDuration = await getDurationFromVideoFile(backupFile)
66 const newDuration = await getDurationFromVideoFile(currentFilePath)
68 if (originalDuration === newDuration) {
69 console.log('Finished optimizing %s', basename(currentFilePath))
70 await remove(backupFile)
74 console.log('Failed to optimize %s, restoring original', basename(currentFilePath))
75 await move(backupFile, currentFilePath, { overwrite: true })
76 await createTorrentAndSetInfoHash(video, file)
82 console.log('Finished optimizing videos')