aboutsummaryrefslogtreecommitdiffhomepage
path: root/scripts/optimize-old-videos.ts
blob: 2c80f16bcf35e40384278b69d9f04d67e8a481b5 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import { VIDEO_TRANSCODING_FPS } from '../server/initializers/constants'
import { getDurationFromVideoFile, getVideoFileBitrate, getVideoFileFPS, getVideoFileResolution } from '../server/helpers/ffmpeg-utils'
import { getMaxBitrate } from '../shared/models/videos'
import { VideoModel } from '../server/models/video/video'
import { optimizeVideofile } from '../server/lib/video-transcoding'
import { initDatabaseModels } from '../server/initializers'
import { basename, dirname, join } from 'path'
import { copy, move, remove } from 'fs-extra'
import { CONFIG } from '../server/initializers/config'

run()
  .then(() => process.exit(0))
  .catch(err => {
    console.error(err)
    process.exit(-1)
  })

let currentVideoId = null
let currentFile = null

process.on('SIGINT', async function () {
  console.log('Cleaning up temp files')
  await remove(`${currentFile}_backup`)
  await remove(`${dirname(currentFile)}/${currentVideoId}-transcoded.mp4`)
  process.exit(0)
})

async function run () {
  await initDatabaseModels(true)

  const localVideos = await VideoModel.listLocal()

  for (const video of localVideos) {
    currentVideoId = video.id

    for (const file of video.VideoFiles) {
      currentFile = join(CONFIG.STORAGE.VIDEOS_DIR, video.getVideoFilename(file))

      const [ videoBitrate, fps, resolution ] = await Promise.all([
        getVideoFileBitrate(currentFile),
        getVideoFileFPS(currentFile),
        getVideoFileResolution(currentFile)
      ])

      const maxBitrate = getMaxBitrate(resolution.videoFileResolution, fps, VIDEO_TRANSCODING_FPS)
      const isMaxBitrateExceeded = videoBitrate > maxBitrate
      if (isMaxBitrateExceeded) {
        console.log(
          'Optimizing video file %s with bitrate %s kbps (max: %s kbps)',
          basename(currentFile), videoBitrate / 1000, maxBitrate / 1000
        )

        const backupFile = `${currentFile}_backup`
        await copy(currentFile, backupFile)

        await optimizeVideofile(video, file)

        const originalDuration = await getDurationFromVideoFile(backupFile)
        const newDuration = await getDurationFromVideoFile(currentFile)

        if (originalDuration === newDuration) {
          console.log('Finished optimizing %s', basename(currentFile))
          await remove(backupFile)
          return
        }

        console.log('Failed to optimize %s, restoring original', basename(currentFile))
        await move(backupFile, currentFile, { overwrite: true })
        await video.createTorrentAndSetInfoHash(file)
        await file.save()
      }
    }
  }

  console.log('Finished optimizing videos')
}