]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame_incremental - server/lib/video-transcoding.ts
Fix audio issues with live replay
[github/Chocobozzz/PeerTube.git] / server / lib / video-transcoding.ts
... / ...
CommitLineData
1import { copyFile, ensureDir, move, remove, stat } from 'fs-extra'
2import { basename, extname as extnameUtil, join } from 'path'
3import { createTorrentAndSetInfoHash } from '@server/helpers/webtorrent'
4import { MStreamingPlaylistFilesVideo, MVideoFile, MVideoWithAllFiles, MVideoWithFile } from '@server/types/models'
5import { VideoResolution } from '../../shared/models/videos'
6import { VideoStreamingPlaylistType } from '../../shared/models/videos/video-streaming-playlist.type'
7import { transcode, TranscodeOptions, TranscodeOptionsType } from '../helpers/ffmpeg-utils'
8import { canDoQuickTranscode, getDurationFromVideoFile, getMetadataFromFile, getVideoFileFPS } from '../helpers/ffprobe-utils'
9import { logger } from '../helpers/logger'
10import { CONFIG } from '../initializers/config'
11import { HLS_STREAMING_PLAYLIST_DIRECTORY, P2P_MEDIA_LOADER_PEER_VERSION, WEBSERVER } from '../initializers/constants'
12import { VideoFileModel } from '../models/video/video-file'
13import { VideoStreamingPlaylistModel } from '../models/video/video-streaming-playlist'
14import { updateMasterHLSPlaylist, updateSha256VODSegments } from './hls'
15import { generateVideoStreamingPlaylistName, getVideoFilename, getVideoFilePath } from './video-paths'
16import { availableEncoders } from './video-transcoding-profiles'
17
18/**
19 *
20 * Functions that run transcoding functions, update the database, cleanup files, create torrent files...
21 * Mainly called by the job queue
22 *
23 */
24
25// Optimize the original video file and replace it. The resolution is not changed.
26async function optimizeOriginalVideofile (video: MVideoWithFile, inputVideoFileArg?: MVideoFile) {
27 const transcodeDirectory = CONFIG.STORAGE.TMP_DIR
28 const newExtname = '.mp4'
29
30 const inputVideoFile = inputVideoFileArg || video.getMaxQualityFile()
31 const videoInputPath = getVideoFilePath(video, inputVideoFile)
32 const videoTranscodedPath = join(transcodeDirectory, video.id + '-transcoded' + newExtname)
33
34 const transcodeType: TranscodeOptionsType = await canDoQuickTranscode(videoInputPath)
35 ? 'quick-transcode'
36 : 'video'
37
38 const transcodeOptions: TranscodeOptions = {
39 type: transcodeType,
40
41 inputPath: videoInputPath,
42 outputPath: videoTranscodedPath,
43
44 availableEncoders,
45 profile: 'default',
46
47 resolution: inputVideoFile.resolution
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
57 inputVideoFile.extname = newExtname
58
59 const videoOutputPath = getVideoFilePath(video, inputVideoFile)
60
61 await onVideoFileTranscoding(video, inputVideoFile, videoTranscodedPath, videoOutputPath)
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
70// Transcode the original video file to a lower resolution.
71async function transcodeNewResolution (video: MVideoWithFile, resolution: VideoResolution, isPortrait: boolean) {
72 const transcodeDirectory = CONFIG.STORAGE.TMP_DIR
73 const extname = '.mp4'
74
75 // We are sure it's x264 in mp4 because optimizeOriginalVideofile was already executed
76 const videoInputPath = getVideoFilePath(video, video.getMaxQualityFile())
77
78 const newVideoFile = new VideoFileModel({
79 resolution,
80 extname,
81 size: 0,
82 videoId: video.id
83 })
84 const videoOutputPath = getVideoFilePath(video, newVideoFile)
85 const videoTranscodedPath = join(transcodeDirectory, getVideoFilename(video, newVideoFile))
86
87 const transcodeOptions = resolution === VideoResolution.H_NOVIDEO
88 ? {
89 type: 'only-audio' as 'only-audio',
90
91 inputPath: videoInputPath,
92 outputPath: videoTranscodedPath,
93
94 availableEncoders,
95 profile: 'default',
96
97 resolution
98 }
99 : {
100 type: 'video' as 'video',
101 inputPath: videoInputPath,
102 outputPath: videoTranscodedPath,
103
104 availableEncoders,
105 profile: 'default',
106
107 resolution,
108 isPortraitMode: isPortrait
109 }
110
111 await transcode(transcodeOptions)
112
113 return onVideoFileTranscoding(video, newVideoFile, videoTranscodedPath, videoOutputPath)
114}
115
116// Merge an image with an audio file to create a video
117async function mergeAudioVideofile (video: MVideoWithAllFiles, resolution: VideoResolution) {
118 const transcodeDirectory = CONFIG.STORAGE.TMP_DIR
119 const newExtname = '.mp4'
120
121 const inputVideoFile = video.getMinQualityFile()
122
123 const audioInputPath = getVideoFilePath(video, inputVideoFile)
124 const videoTranscodedPath = join(transcodeDirectory, video.id + '-transcoded' + newExtname)
125
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
131 const transcodeOptions = {
132 type: 'merge-audio' as 'merge-audio',
133
134 inputPath: tmpPreviewPath,
135 outputPath: videoTranscodedPath,
136
137 availableEncoders,
138 profile: 'default',
139
140 audioPath: audioInputPath,
141 resolution
142 }
143
144 try {
145 await transcode(transcodeOptions)
146
147 await remove(audioInputPath)
148 await remove(tmpPreviewPath)
149 } catch (err) {
150 await remove(tmpPreviewPath)
151 throw err
152 }
153
154 // Important to do this before getVideoFilename() to take in account the new file extension
155 inputVideoFile.extname = newExtname
156
157 const videoOutputPath = getVideoFilePath(video, inputVideoFile)
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()
162
163 return onVideoFileTranscoding(video, inputVideoFile, videoTranscodedPath, videoOutputPath)
164}
165
166// Concat TS segments from a live video to a fragmented mp4 HLS playlist
167async function generateHlsPlaylistFromTS (options: {
168 video: MVideoWithFile
169 concatenatedTsFilePath: string
170 resolution: VideoResolution
171 isPortraitMode: boolean
172}) {
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 })
180}
181
182// Generate an HLS playlist from an input file, and update the master playlist
183function generateHlsPlaylist (options: {
184 video: MVideoWithFile
185 videoInputPath: string
186 resolution: VideoResolution
187 copyCodecs: boolean
188 isPortraitMode: boolean
189}) {
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
240
241 const baseHlsDirectory = join(HLS_STREAMING_PLAYLIST_DIRECTORY, video.uuid)
242 await ensureDir(join(HLS_STREAMING_PLAYLIST_DIRECTORY, video.uuid))
243
244 const outputPath = join(baseHlsDirectory, VideoStreamingPlaylistModel.getHlsPlaylistFilename(resolution))
245 const videoFilename = generateVideoStreamingPlaylistName(video.uuid, resolution)
246
247 const transcodeOptions = {
248 type,
249
250 inputPath,
251 outputPath,
252
253 availableEncoders,
254 profile: 'default',
255
256 resolution,
257 copyCodecs,
258 isPortraitMode,
259
260 hlsPlaylist: {
261 videoFilename
262 }
263 }
264
265 await transcode(transcodeOptions)
266
267 const playlistUrl = WEBSERVER.URL + VideoStreamingPlaylistModel.getHlsMasterPlaylistStaticPath(video.uuid)
268
269 const [ videoStreamingPlaylist ] = await VideoStreamingPlaylistModel.upsert({
270 videoId: video.id,
271 playlistUrl,
272 segmentsSha256Url: WEBSERVER.URL + VideoStreamingPlaylistModel.getHlsSha256SegmentsStaticPath(video.uuid, video.isLive),
273 p2pMediaLoaderInfohashes: [],
274 p2pMediaLoaderPeerVersion: P2P_MEDIA_LOADER_PEER_VERSION,
275
276 type: VideoStreamingPlaylistType.HLS
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
286 })
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)
293 newVideoFile.metadata = await getMetadataFromFile(videoFilePath)
294
295 await createTorrentAndSetInfoHash(videoStreamingPlaylist, newVideoFile)
296
297 await VideoFileModel.customUpsert(newVideoFile, 'streaming-playlist', undefined)
298 videoStreamingPlaylist.VideoFiles = await videoStreamingPlaylist.$get('VideoFiles')
299
300 videoStreamingPlaylist.p2pMediaLoaderInfohashes = VideoStreamingPlaylistModel.buildP2PMediaLoaderInfoHashes(
301 playlistUrl, videoStreamingPlaylist.VideoFiles
302 )
303 await videoStreamingPlaylist.save()
304
305 video.setHLSPlaylist(videoStreamingPlaylist)
306
307 await updateMasterHLSPlaylist(video)
308 await updateSha256VODSegments(video)
309
310 return outputPath
311}