]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/lib/video-transcoding.ts
Fix audio issues with live replay
[github/Chocobozzz/PeerTube.git] / server / lib / video-transcoding.ts
CommitLineData
3851e732 1import { copyFile, ensureDir, move, remove, stat } 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
3851e732 169 concatenatedTsFilePath: string
2650d6d4
C
170 resolution: VideoResolution
171 isPortraitMode: boolean
172}) {
3851e732
C
173 return generateHlsPlaylistCommon({
174 video: options.video,
175 resolution: options.resolution,
176 isPortraitMode: options.isPortraitMode,
177 inputPath: options.concatenatedTsFilePath,
178 type: 'hls-from-ts' as 'hls-from-ts'
179 })
2650d6d4
C
180}
181
6b67897e 182// Generate an HLS playlist from an input file, and update the master playlist
2650d6d4 183function generateHlsPlaylist (options: {
b5b68755
C
184 video: MVideoWithFile
185 videoInputPath: string
186 resolution: VideoResolution
187 copyCodecs: boolean
188 isPortraitMode: boolean
189}) {
2650d6d4
C
190 return generateHlsPlaylistCommon({
191 video: options.video,
192 resolution: options.resolution,
193 copyCodecs: options.copyCodecs,
194 isPortraitMode: options.isPortraitMode,
195 inputPath: options.videoInputPath,
196 type: 'hls' as 'hls'
197 })
198}
199
200// ---------------------------------------------------------------------------
201
202export {
203 generateHlsPlaylist,
204 generateHlsPlaylistFromTS,
205 optimizeOriginalVideofile,
206 transcodeNewResolution,
207 mergeAudioVideofile
208}
209
210// ---------------------------------------------------------------------------
211
212async function onVideoFileTranscoding (video: MVideoWithFile, videoFile: MVideoFile, transcodingPath: string, outputPath: string) {
213 const stats = await stat(transcodingPath)
214 const fps = await getVideoFileFPS(transcodingPath)
215 const metadata = await getMetadataFromFile(transcodingPath)
216
217 await move(transcodingPath, outputPath, { overwrite: true })
218
219 videoFile.size = stats.size
220 videoFile.fps = fps
221 videoFile.metadata = metadata
222
223 await createTorrentAndSetInfoHash(video, videoFile)
224
225 await VideoFileModel.customUpsert(videoFile, 'video', undefined)
226 video.VideoFiles = await video.$get('VideoFiles')
227
228 return video
229}
230
231async function generateHlsPlaylistCommon (options: {
232 type: 'hls' | 'hls-from-ts'
233 video: MVideoWithFile
234 inputPath: string
235 resolution: VideoResolution
236 copyCodecs?: boolean
237 isPortraitMode: boolean
238}) {
239 const { type, video, inputPath, resolution, copyCodecs, isPortraitMode } = options
b5b68755 240
9c6ca37f
C
241 const baseHlsDirectory = join(HLS_STREAMING_PLAYLIST_DIRECTORY, video.uuid)
242 await ensureDir(join(HLS_STREAMING_PLAYLIST_DIRECTORY, video.uuid))
09209296 243
09209296 244 const outputPath = join(baseHlsDirectory, VideoStreamingPlaylistModel.getHlsPlaylistFilename(resolution))
d7a25329 245 const videoFilename = generateVideoStreamingPlaylistName(video.uuid, resolution)
09209296
C
246
247 const transcodeOptions = {
2650d6d4 248 type,
9252a33d 249
2650d6d4 250 inputPath,
09209296 251 outputPath,
9252a33d
C
252
253 availableEncoders,
254 profile: 'default',
255
09209296 256 resolution,
d7a25329 257 copyCodecs,
09209296 258 isPortraitMode,
4c280004
C
259
260 hlsPlaylist: {
d7a25329 261 videoFilename
4c280004 262 }
09209296
C
263 }
264
d7a25329 265 await transcode(transcodeOptions)
09209296 266
6dd9de95 267 const playlistUrl = WEBSERVER.URL + VideoStreamingPlaylistModel.getHlsMasterPlaylistStaticPath(video.uuid)
09209296 268
d7a25329 269 const [ videoStreamingPlaylist ] = await VideoStreamingPlaylistModel.upsert({
09209296
C
270 videoId: video.id,
271 playlistUrl,
c6c0fa6c 272 segmentsSha256Url: WEBSERVER.URL + VideoStreamingPlaylistModel.getHlsSha256SegmentsStaticPath(video.uuid, video.isLive),
b5b68755 273 p2pMediaLoaderInfohashes: [],
594d0c6a 274 p2pMediaLoaderPeerVersion: P2P_MEDIA_LOADER_PEER_VERSION,
09209296
C
275
276 type: VideoStreamingPlaylistType.HLS
d7a25329
C
277 }, { returning: true }) as [ MStreamingPlaylistFilesVideo, boolean ]
278 videoStreamingPlaylist.Video = video
279
280 const newVideoFile = new VideoFileModel({
281 resolution,
282 extname: extnameUtil(videoFilename),
283 size: 0,
284 fps: -1,
285 videoStreamingPlaylistId: videoStreamingPlaylist.id
09209296 286 })
d7a25329
C
287
288 const videoFilePath = getVideoFilePath(videoStreamingPlaylist, newVideoFile)
289 const stats = await stat(videoFilePath)
290
291 newVideoFile.size = stats.size
292 newVideoFile.fps = await getVideoFileFPS(videoFilePath)
8319d6ae 293 newVideoFile.metadata = await getMetadataFromFile(videoFilePath)
d7a25329
C
294
295 await createTorrentAndSetInfoHash(videoStreamingPlaylist, newVideoFile)
296
c547bbf9 297 await VideoFileModel.customUpsert(newVideoFile, 'streaming-playlist', undefined)
e6122097 298 videoStreamingPlaylist.VideoFiles = await videoStreamingPlaylist.$get('VideoFiles')
d7a25329 299
b5b68755
C
300 videoStreamingPlaylist.p2pMediaLoaderInfohashes = VideoStreamingPlaylistModel.buildP2PMediaLoaderInfoHashes(
301 playlistUrl, videoStreamingPlaylist.VideoFiles
302 )
303 await videoStreamingPlaylist.save()
304
d7a25329
C
305 video.setHLSPlaylist(videoStreamingPlaylist)
306
307 await updateMasterHLSPlaylist(video)
c6c0fa6c 308 await updateSha256VODSegments(video)
d7a25329 309
2650d6d4 310 return outputPath
098eb377 311}