]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blobdiff - server/lib/video-transcoding.ts
Upgrade sequelize to v6
[github/Chocobozzz/PeerTube.git] / server / lib / video-transcoding.ts
index 0e6a0e9840e12dca5c71445f903875e7de1af632..e7108bd5a971dd9fec05673273d06beffd131643 100644 (file)
@@ -2,34 +2,27 @@ import { copyFile, ensureDir, move, remove, stat } from 'fs-extra'
 import { basename, extname as extnameUtil, join } from 'path'
 import { createTorrentAndSetInfoHash } from '@server/helpers/webtorrent'
 import { MStreamingPlaylistFilesVideo, MVideoFile, MVideoWithAllFiles, MVideoWithFile } from '@server/types/models'
-import { getTargetBitrate, VideoResolution } from '../../shared/models/videos'
+import { VideoResolution } from '../../shared/models/videos'
 import { VideoStreamingPlaylistType } from '../../shared/models/videos/video-streaming-playlist.type'
-import { AvailableEncoders, EncoderOptionsBuilder, transcode, TranscodeOptions, TranscodeOptionsType } from '../helpers/ffmpeg-utils'
-import {
-  canDoQuickTranscode,
-  getAudioStream,
-  getDurationFromVideoFile,
-  getMaxAudioBitrate,
-  getMetadataFromFile,
-  getVideoFileBitrate,
-  getVideoFileFPS
-} from '../helpers/ffprobe-utils'
+import { transcode, TranscodeOptions, TranscodeOptionsType } from '../helpers/ffmpeg-utils'
+import { canDoQuickTranscode, getDurationFromVideoFile, getMetadataFromFile, getVideoFileFPS } from '../helpers/ffprobe-utils'
 import { logger } from '../helpers/logger'
 import { CONFIG } from '../initializers/config'
-import {
-  HLS_STREAMING_PLAYLIST_DIRECTORY,
-  P2P_MEDIA_LOADER_PEER_VERSION,
-  VIDEO_TRANSCODING_FPS,
-  WEBSERVER
-} from '../initializers/constants'
+import { HLS_STREAMING_PLAYLIST_DIRECTORY, P2P_MEDIA_LOADER_PEER_VERSION, WEBSERVER } from '../initializers/constants'
 import { VideoFileModel } from '../models/video/video-file'
 import { VideoStreamingPlaylistModel } from '../models/video/video-streaming-playlist'
 import { updateMasterHLSPlaylist, updateSha256VODSegments } from './hls'
 import { generateVideoStreamingPlaylistName, getVideoFilename, getVideoFilePath } from './video-paths'
+import { availableEncoders } from './video-transcoding-profiles'
 
 /**
- * Optimize the original video file and replace it. The resolution is not changed.
+ *
+ * Functions that run transcoding functions, update the database, cleanup files, create torrent files...
+ * Mainly called by the job queue
+ *
  */
+
+// Optimize the original video file and replace it. The resolution is not changed.
 async function optimizeOriginalVideofile (video: MVideoWithFile, inputVideoFileArg?: MVideoFile) {
   const transcodeDirectory = CONFIG.STORAGE.TMP_DIR
   const newExtname = '.mp4'
@@ -74,9 +67,7 @@ async function optimizeOriginalVideofile (video: MVideoWithFile, inputVideoFileA
   }
 }
 
-/**
- * Transcode the original video file to a lower resolution.
- */
+// Transcode the original video file to a lower resolution.
 async function transcodeNewResolution (video: MVideoWithFile, resolution: VideoResolution, isPortrait: boolean) {
   const transcodeDirectory = CONFIG.STORAGE.TMP_DIR
   const extname = '.mp4'
@@ -122,6 +113,7 @@ async function transcodeNewResolution (video: MVideoWithFile, resolution: VideoR
   return onVideoFileTranscoding(video, newVideoFile, videoTranscodedPath, videoOutputPath)
 }
 
+// Merge an image with an audio file to create a video
 async function mergeAudioVideofile (video: MVideoWithAllFiles, resolution: VideoResolution) {
   const transcodeDirectory = CONFIG.STORAGE.TMP_DIR
   const newExtname = '.mp4'
@@ -171,14 +163,83 @@ async function mergeAudioVideofile (video: MVideoWithAllFiles, resolution: Video
   return onVideoFileTranscoding(video, inputVideoFile, videoTranscodedPath, videoOutputPath)
 }
 
-async function generateHlsPlaylist (options: {
+// Concat TS segments from a live video to a fragmented mp4 HLS playlist
+async function generateHlsPlaylistFromTS (options: {
+  video: MVideoWithFile
+  concatenatedTsFilePath: string
+  resolution: VideoResolution
+  isPortraitMode: boolean
+  isAAC: boolean
+}) {
+  return generateHlsPlaylistCommon({
+    video: options.video,
+    resolution: options.resolution,
+    isPortraitMode: options.isPortraitMode,
+    inputPath: options.concatenatedTsFilePath,
+    type: 'hls-from-ts' as 'hls-from-ts',
+    isAAC: options.isAAC
+  })
+}
+
+// Generate an HLS playlist from an input file, and update the master playlist
+function generateHlsPlaylist (options: {
   video: MVideoWithFile
   videoInputPath: string
   resolution: VideoResolution
   copyCodecs: boolean
   isPortraitMode: boolean
 }) {
-  const { video, videoInputPath, resolution, copyCodecs, isPortraitMode } = options
+  return generateHlsPlaylistCommon({
+    video: options.video,
+    resolution: options.resolution,
+    copyCodecs: options.copyCodecs,
+    isPortraitMode: options.isPortraitMode,
+    inputPath: options.videoInputPath,
+    type: 'hls' as 'hls'
+  })
+}
+
+// ---------------------------------------------------------------------------
+
+export {
+  generateHlsPlaylist,
+  generateHlsPlaylistFromTS,
+  optimizeOriginalVideofile,
+  transcodeNewResolution,
+  mergeAudioVideofile
+}
+
+// ---------------------------------------------------------------------------
+
+async function onVideoFileTranscoding (video: MVideoWithFile, videoFile: MVideoFile, transcodingPath: string, outputPath: string) {
+  const stats = await stat(transcodingPath)
+  const fps = await getVideoFileFPS(transcodingPath)
+  const metadata = await getMetadataFromFile(transcodingPath)
+
+  await move(transcodingPath, outputPath, { overwrite: true })
+
+  videoFile.size = stats.size
+  videoFile.fps = fps
+  videoFile.metadata = metadata
+
+  await createTorrentAndSetInfoHash(video, videoFile)
+
+  await VideoFileModel.customUpsert(videoFile, 'video', undefined)
+  video.VideoFiles = await video.$get('VideoFiles')
+
+  return video
+}
+
+async function generateHlsPlaylistCommon (options: {
+  type: 'hls' | 'hls-from-ts'
+  video: MVideoWithFile
+  inputPath: string
+  resolution: VideoResolution
+  copyCodecs?: boolean
+  isAAC?: boolean
+  isPortraitMode: boolean
+}) {
+  const { type, video, inputPath, resolution, copyCodecs, isPortraitMode, isAAC } = options
 
   const baseHlsDirectory = join(HLS_STREAMING_PLAYLIST_DIRECTORY, video.uuid)
   await ensureDir(join(HLS_STREAMING_PLAYLIST_DIRECTORY, video.uuid))
@@ -187,9 +248,9 @@ async function generateHlsPlaylist (options: {
   const videoFilename = generateVideoStreamingPlaylistName(video.uuid, resolution)
 
   const transcodeOptions = {
-    type: 'hls' as 'hls',
+    type,
 
-    inputPath: videoInputPath,
+    inputPath,
     outputPath,
 
     availableEncoders,
@@ -199,6 +260,8 @@ async function generateHlsPlaylist (options: {
     copyCodecs,
     isPortraitMode,
 
+    isAAC,
+
     hlsPlaylist: {
       videoFilename
     }
@@ -249,104 +312,5 @@ async function generateHlsPlaylist (options: {
   await updateMasterHLSPlaylist(video)
   await updateSha256VODSegments(video)
 
-  return video
-}
-
-// ---------------------------------------------------------------------------
-// Available encoders profiles
-// ---------------------------------------------------------------------------
-
-const defaultX264OptionsBuilder: EncoderOptionsBuilder = async ({ input, resolution, fps }) => {
-  if (!fps) return { outputOptions: [] }
-
-  let targetBitrate = getTargetBitrate(resolution, fps, VIDEO_TRANSCODING_FPS)
-
-  // Don't transcode to an higher bitrate than the original file
-  const fileBitrate = await getVideoFileBitrate(input)
-  targetBitrate = Math.min(targetBitrate, fileBitrate)
-
-  return {
-    outputOptions: [
-      // Constrained Encoding (VBV)
-      // https://slhck.info/video/2017/03/01/rate-control.html
-      // https://trac.ffmpeg.org/wiki/Limiting%20the%20output%20bitrate
-      `-maxrate ${targetBitrate}`, `-bufsize ${targetBitrate * 2}`
-    ]
-  }
-}
-
-const defaultAACOptionsBuilder: EncoderOptionsBuilder = async ({ input }) => {
-  const parsedAudio = await getAudioStream(input)
-
-  // we try to reduce the ceiling bitrate by making rough matches of bitrates
-  // of course this is far from perfect, but it might save some space in the end
-
-  const audioCodecName = parsedAudio.audioStream['codec_name']
-
-  const bitrate = getMaxAudioBitrate(audioCodecName, parsedAudio.bitrate)
-
-  if (bitrate !== undefined && bitrate !== -1) {
-    return { outputOptions: [ '-b:a', bitrate + 'k' ] }
-  }
-
-  return { outputOptions: [] }
-}
-
-const defaultLibFDKAACOptionsBuilder: EncoderOptionsBuilder = () => {
-  return { outputOptions: [ '-aq', '5' ] }
-}
-
-const availableEncoders: AvailableEncoders = {
-  vod: {
-    libx264: {
-      default: defaultX264OptionsBuilder
-    },
-    aac: {
-      default: defaultAACOptionsBuilder
-    },
-    libfdkAAC: {
-      default: defaultLibFDKAACOptionsBuilder
-    }
-  },
-  live: {
-    libx264: {
-      default: defaultX264OptionsBuilder
-    },
-    aac: {
-      default: defaultAACOptionsBuilder
-    },
-    libfdkAAC: {
-      default: defaultLibFDKAACOptionsBuilder
-    }
-  }
-}
-
-// ---------------------------------------------------------------------------
-
-export {
-  generateHlsPlaylist,
-  optimizeOriginalVideofile,
-  transcodeNewResolution,
-  mergeAudioVideofile
-}
-
-// ---------------------------------------------------------------------------
-
-async function onVideoFileTranscoding (video: MVideoWithFile, videoFile: MVideoFile, transcodingPath: string, outputPath: string) {
-  const stats = await stat(transcodingPath)
-  const fps = await getVideoFileFPS(transcodingPath)
-  const metadata = await getMetadataFromFile(transcodingPath)
-
-  await move(transcodingPath, outputPath, { overwrite: true })
-
-  videoFile.size = stats.size
-  videoFile.fps = fps
-  videoFile.metadata = metadata
-
-  await createTorrentAndSetInfoHash(video, videoFile)
-
-  await VideoFileModel.customUpsert(videoFile, 'video', undefined)
-  video.VideoFiles = await video.$get('VideoFiles')
-
-  return video
+  return outputPath
 }