]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/lib/video-transcoding.ts
Try to fix live freeze
[github/Chocobozzz/PeerTube.git] / server / lib / video-transcoding.ts
CommitLineData
2650d6d4 1import { copyFile, ensureDir, move, remove, stat, writeFile } from 'fs-extra'
d7a25329 2import { basename, extname as extnameUtil, join } from 'path'
053aed43
C
3import { createTorrentAndSetInfoHash } from '@server/helpers/webtorrent'
4import { MStreamingPlaylistFilesVideo, MVideoFile, MVideoWithAllFiles, MVideoWithFile } from '@server/types/models'
5a547f69 5import { VideoResolution } from '../../shared/models/videos'
053aed43 6import { VideoStreamingPlaylistType } from '../../shared/models/videos/video-streaming-playlist.type'
5a547f69
C
7import { transcode, TranscodeOptions, TranscodeOptionsType } from '../helpers/ffmpeg-utils'
8import { canDoQuickTranscode, getDurationFromVideoFile, getMetadataFromFile, getVideoFileFPS } from '../helpers/ffprobe-utils'
098eb377 9import { logger } from '../helpers/logger'
053aed43 10import { CONFIG } from '../initializers/config'
5a547f69 11import { HLS_STREAMING_PLAYLIST_DIRECTORY, P2P_MEDIA_LOADER_PEER_VERSION, WEBSERVER } from '../initializers/constants'
098eb377 12import { VideoFileModel } from '../models/video/video-file'
09209296 13import { VideoStreamingPlaylistModel } from '../models/video/video-streaming-playlist'
053aed43 14import { updateMasterHLSPlaylist, updateSha256VODSegments } from './hls'
d7a25329 15import { generateVideoStreamingPlaylistName, getVideoFilename, getVideoFilePath } from './video-paths'
5a547f69 16import { availableEncoders } from './video-transcoding-profiles'
098eb377 17
658a47ab 18/**
6b67897e
C
19 *
20 * Functions that run transcoding functions, update the database, cleanup files, create torrent files...
21 * Mainly called by the job queue
22 *
658a47ab 23 */
6b67897e
C
24
25// Optimize the original video file and replace it. The resolution is not changed.
d7a25329 26async function optimizeOriginalVideofile (video: MVideoWithFile, inputVideoFileArg?: MVideoFile) {
2fbd5e25 27 const transcodeDirectory = CONFIG.STORAGE.TMP_DIR
098eb377 28 const newExtname = '.mp4'
9f1ddd24 29
d7a25329
C
30 const inputVideoFile = inputVideoFileArg || video.getMaxQualityFile()
31 const videoInputPath = getVideoFilePath(video, inputVideoFile)
2fbd5e25 32 const videoTranscodedPath = join(transcodeDirectory, video.id + '-transcoded' + newExtname)
098eb377 33
536598cf
C
34 const transcodeType: TranscodeOptionsType = await canDoQuickTranscode(videoInputPath)
35 ? 'quick-transcode'
36 : 'video'
5ba49f26 37
536598cf 38 const transcodeOptions: TranscodeOptions = {
d7a25329 39 type: transcodeType,
9252a33d 40
098eb377 41 inputPath: videoInputPath,
09209296 42 outputPath: videoTranscodedPath,
9252a33d
C
43
44 availableEncoders,
45 profile: 'default',
46
536598cf 47 resolution: inputVideoFile.resolution
098eb377
C
48 }
49
50 // Could be very long!
51 await transcode(transcodeOptions)
52
53 try {
54 await remove(videoInputPath)
55
56 // Important to do this before getVideoFilename() to take in account the new file extension
536598cf 57 inputVideoFile.extname = newExtname
2fbd5e25 58
d7a25329 59 const videoOutputPath = getVideoFilePath(video, inputVideoFile)
098eb377 60
536598cf 61 await onVideoFileTranscoding(video, inputVideoFile, videoTranscodedPath, videoOutputPath)
098eb377
C
62 } catch (err) {
63 // Auto destruction...
64 video.destroy().catch(err => logger.error('Cannot destruct video after transcoding failure.', { err }))
65
66 throw err
67 }
68}
69
6b67897e 70// Transcode the original video file to a lower resolution.
d7a25329 71async function transcodeNewResolution (video: MVideoWithFile, resolution: VideoResolution, isPortrait: boolean) {
2fbd5e25 72 const transcodeDirectory = CONFIG.STORAGE.TMP_DIR
098eb377
C
73 const extname = '.mp4'
74
75 // We are sure it's x264 in mp4 because optimizeOriginalVideofile was already executed
d7a25329 76 const videoInputPath = getVideoFilePath(video, video.getMaxQualityFile())
098eb377
C
77
78 const newVideoFile = new VideoFileModel({
79 resolution,
80 extname,
81 size: 0,
82 videoId: video.id
83 })
d7a25329
C
84 const videoOutputPath = getVideoFilePath(video, newVideoFile)
85 const videoTranscodedPath = join(transcodeDirectory, getVideoFilename(video, newVideoFile))
098eb377 86
5c7d6508 87 const transcodeOptions = resolution === VideoResolution.H_NOVIDEO
88 ? {
3a149e9f 89 type: 'only-audio' as 'only-audio',
9252a33d 90
3a149e9f
C
91 inputPath: videoInputPath,
92 outputPath: videoTranscodedPath,
9252a33d
C
93
94 availableEncoders,
95 profile: 'default',
96
3a149e9f
C
97 resolution
98 }
5c7d6508 99 : {
3a149e9f
C
100 type: 'video' as 'video',
101 inputPath: videoInputPath,
102 outputPath: videoTranscodedPath,
9252a33d
C
103
104 availableEncoders,
105 profile: 'default',
106
3a149e9f
C
107 resolution,
108 isPortraitMode: isPortrait
109 }
098eb377
C
110
111 await transcode(transcodeOptions)
112
536598cf
C
113 return onVideoFileTranscoding(video, newVideoFile, videoTranscodedPath, videoOutputPath)
114}
115
6b67897e 116// Merge an image with an audio file to create a video
d7a25329 117async function mergeAudioVideofile (video: MVideoWithAllFiles, resolution: VideoResolution) {
536598cf
C
118 const transcodeDirectory = CONFIG.STORAGE.TMP_DIR
119 const newExtname = '.mp4'
120
92e0f42e 121 const inputVideoFile = video.getMinQualityFile()
2fbd5e25 122
d7a25329 123 const audioInputPath = getVideoFilePath(video, inputVideoFile)
536598cf 124 const videoTranscodedPath = join(transcodeDirectory, video.id + '-transcoded' + newExtname)
098eb377 125
eba06469
C
126 // If the user updates the video preview during transcoding
127 const previewPath = video.getPreview().getPath()
128 const tmpPreviewPath = join(CONFIG.STORAGE.TMP_DIR, basename(previewPath))
129 await copyFile(previewPath, tmpPreviewPath)
130
536598cf
C
131 const transcodeOptions = {
132 type: 'merge-audio' as 'merge-audio',
9252a33d 133
eba06469 134 inputPath: tmpPreviewPath,
536598cf 135 outputPath: videoTranscodedPath,
9252a33d
C
136
137 availableEncoders,
138 profile: 'default',
139
536598cf
C
140 audioPath: audioInputPath,
141 resolution
142 }
098eb377 143
eba06469
C
144 try {
145 await transcode(transcodeOptions)
098eb377 146
eba06469
C
147 await remove(audioInputPath)
148 await remove(tmpPreviewPath)
149 } catch (err) {
150 await remove(tmpPreviewPath)
151 throw err
152 }
098eb377 153
536598cf
C
154 // Important to do this before getVideoFilename() to take in account the new file extension
155 inputVideoFile.extname = newExtname
156
d7a25329 157 const videoOutputPath = getVideoFilePath(video, inputVideoFile)
eba06469
C
158 // ffmpeg generated a new video file, so update the video duration
159 // See https://trac.ffmpeg.org/ticket/5456
160 video.duration = await getDurationFromVideoFile(videoTranscodedPath)
161 await video.save()
536598cf
C
162
163 return onVideoFileTranscoding(video, inputVideoFile, videoTranscodedPath, videoOutputPath)
098eb377
C
164}
165
2650d6d4
C
166// Concat TS segments from a live video to a fragmented mp4 HLS playlist
167async function generateHlsPlaylistFromTS (options: {
168 video: MVideoWithFile
169 replayDirectory: string
170 segmentFiles: string[]
171 resolution: VideoResolution
172 isPortraitMode: boolean
173}) {
174 const concatFilePath = join(options.replayDirectory, 'concat.txt')
175
176 function cleaner () {
177 remove(concatFilePath)
178 .catch(err => logger.error('Cannot remove concat file in %s.', options.replayDirectory, { err }))
179 }
180
181 // First concat the ts files to a mp4 file
182 const content = options.segmentFiles.map(f => 'file ' + f)
183 .join('\n')
184
185 await writeFile(concatFilePath, content + '\n')
186
187 try {
188 const outputPath = await generateHlsPlaylistCommon({
189 video: options.video,
190 resolution: options.resolution,
191 isPortraitMode: options.isPortraitMode,
192 inputPath: concatFilePath,
193 type: 'hls-from-ts' as 'hls-from-ts'
194 })
195
196 cleaner()
197
198 return outputPath
199 } catch (err) {
200 cleaner()
201
202 throw err
203 }
204}
205
6b67897e 206// Generate an HLS playlist from an input file, and update the master playlist
2650d6d4 207function generateHlsPlaylist (options: {
b5b68755
C
208 video: MVideoWithFile
209 videoInputPath: string
210 resolution: VideoResolution
211 copyCodecs: boolean
212 isPortraitMode: boolean
213}) {
2650d6d4
C
214 return generateHlsPlaylistCommon({
215 video: options.video,
216 resolution: options.resolution,
217 copyCodecs: options.copyCodecs,
218 isPortraitMode: options.isPortraitMode,
219 inputPath: options.videoInputPath,
220 type: 'hls' as 'hls'
221 })
222}
223
224// ---------------------------------------------------------------------------
225
226export {
227 generateHlsPlaylist,
228 generateHlsPlaylistFromTS,
229 optimizeOriginalVideofile,
230 transcodeNewResolution,
231 mergeAudioVideofile
232}
233
234// ---------------------------------------------------------------------------
235
236async function onVideoFileTranscoding (video: MVideoWithFile, videoFile: MVideoFile, transcodingPath: string, outputPath: string) {
237 const stats = await stat(transcodingPath)
238 const fps = await getVideoFileFPS(transcodingPath)
239 const metadata = await getMetadataFromFile(transcodingPath)
240
241 await move(transcodingPath, outputPath, { overwrite: true })
242
243 videoFile.size = stats.size
244 videoFile.fps = fps
245 videoFile.metadata = metadata
246
247 await createTorrentAndSetInfoHash(video, videoFile)
248
249 await VideoFileModel.customUpsert(videoFile, 'video', undefined)
250 video.VideoFiles = await video.$get('VideoFiles')
251
252 return video
253}
254
255async function generateHlsPlaylistCommon (options: {
256 type: 'hls' | 'hls-from-ts'
257 video: MVideoWithFile
258 inputPath: string
259 resolution: VideoResolution
260 copyCodecs?: boolean
261 isPortraitMode: boolean
262}) {
263 const { type, video, inputPath, resolution, copyCodecs, isPortraitMode } = options
b5b68755 264
9c6ca37f
C
265 const baseHlsDirectory = join(HLS_STREAMING_PLAYLIST_DIRECTORY, video.uuid)
266 await ensureDir(join(HLS_STREAMING_PLAYLIST_DIRECTORY, video.uuid))
09209296 267
09209296 268 const outputPath = join(baseHlsDirectory, VideoStreamingPlaylistModel.getHlsPlaylistFilename(resolution))
d7a25329 269 const videoFilename = generateVideoStreamingPlaylistName(video.uuid, resolution)
09209296
C
270
271 const transcodeOptions = {
2650d6d4 272 type,
9252a33d 273
2650d6d4 274 inputPath,
09209296 275 outputPath,
9252a33d
C
276
277 availableEncoders,
278 profile: 'default',
279
09209296 280 resolution,
d7a25329 281 copyCodecs,
09209296 282 isPortraitMode,
4c280004
C
283
284 hlsPlaylist: {
d7a25329 285 videoFilename
4c280004 286 }
09209296
C
287 }
288
d7a25329 289 await transcode(transcodeOptions)
09209296 290
6dd9de95 291 const playlistUrl = WEBSERVER.URL + VideoStreamingPlaylistModel.getHlsMasterPlaylistStaticPath(video.uuid)
09209296 292
d7a25329 293 const [ videoStreamingPlaylist ] = await VideoStreamingPlaylistModel.upsert({
09209296
C
294 videoId: video.id,
295 playlistUrl,
c6c0fa6c 296 segmentsSha256Url: WEBSERVER.URL + VideoStreamingPlaylistModel.getHlsSha256SegmentsStaticPath(video.uuid, video.isLive),
b5b68755 297 p2pMediaLoaderInfohashes: [],
594d0c6a 298 p2pMediaLoaderPeerVersion: P2P_MEDIA_LOADER_PEER_VERSION,
09209296
C
299
300 type: VideoStreamingPlaylistType.HLS
d7a25329
C
301 }, { returning: true }) as [ MStreamingPlaylistFilesVideo, boolean ]
302 videoStreamingPlaylist.Video = video
303
304 const newVideoFile = new VideoFileModel({
305 resolution,
306 extname: extnameUtil(videoFilename),
307 size: 0,
308 fps: -1,
309 videoStreamingPlaylistId: videoStreamingPlaylist.id
09209296 310 })
d7a25329
C
311
312 const videoFilePath = getVideoFilePath(videoStreamingPlaylist, newVideoFile)
313 const stats = await stat(videoFilePath)
314
315 newVideoFile.size = stats.size
316 newVideoFile.fps = await getVideoFileFPS(videoFilePath)
8319d6ae 317 newVideoFile.metadata = await getMetadataFromFile(videoFilePath)
d7a25329
C
318
319 await createTorrentAndSetInfoHash(videoStreamingPlaylist, newVideoFile)
320
c547bbf9 321 await VideoFileModel.customUpsert(newVideoFile, 'streaming-playlist', undefined)
e6122097 322 videoStreamingPlaylist.VideoFiles = await videoStreamingPlaylist.$get('VideoFiles')
d7a25329 323
b5b68755
C
324 videoStreamingPlaylist.p2pMediaLoaderInfohashes = VideoStreamingPlaylistModel.buildP2PMediaLoaderInfoHashes(
325 playlistUrl, videoStreamingPlaylist.VideoFiles
326 )
327 await videoStreamingPlaylist.save()
328
d7a25329
C
329 video.setHLSPlaylist(videoStreamingPlaylist)
330
331 await updateMasterHLSPlaylist(video)
c6c0fa6c 332 await updateSha256VODSegments(video)
d7a25329 333
2650d6d4 334 return outputPath
098eb377 335}