]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/lib/video-transcoding.ts
Dissociate video file names and video uuid
[github/Chocobozzz/PeerTube.git] / server / lib / video-transcoding.ts
1 import { Job } from 'bull'
2 import { copyFile, ensureDir, move, remove, stat } from 'fs-extra'
3 import { basename, extname as extnameUtil, join } from 'path'
4 import { createTorrentAndSetInfoHash } from '@server/helpers/webtorrent'
5 import { MStreamingPlaylistFilesVideo, MVideoFile, MVideoFullLight } from '@server/types/models'
6 import { VideoResolution } from '../../shared/models/videos'
7 import { VideoStreamingPlaylistType } from '../../shared/models/videos/video-streaming-playlist.type'
8 import { transcode, TranscodeOptions, TranscodeOptionsType } from '../helpers/ffmpeg-utils'
9 import { canDoQuickTranscode, getDurationFromVideoFile, getMetadataFromFile, getVideoFileFPS } from '../helpers/ffprobe-utils'
10 import { logger } from '../helpers/logger'
11 import { CONFIG } from '../initializers/config'
12 import { HLS_STREAMING_PLAYLIST_DIRECTORY, P2P_MEDIA_LOADER_PEER_VERSION, WEBSERVER } from '../initializers/constants'
13 import { VideoFileModel } from '../models/video/video-file'
14 import { VideoStreamingPlaylistModel } from '../models/video/video-streaming-playlist'
15 import { updateMasterHLSPlaylist, updateSha256VODSegments } from './hls'
16 import { generateVideoFilename, generateVideoStreamingPlaylistName, getVideoFilePath } from './video-paths'
17 import { VideoTranscodingProfilesManager } from './video-transcoding-profiles'
18
19 /**
20 *
21 * Functions that run transcoding functions, update the database, cleanup files, create torrent files...
22 * Mainly called by the job queue
23 *
24 */
25
26 // Optimize the original video file and replace it. The resolution is not changed.
27 async function optimizeOriginalVideofile (video: MVideoFullLight, inputVideoFile: MVideoFile, job?: Job) {
28 const transcodeDirectory = CONFIG.STORAGE.TMP_DIR
29 const newExtname = '.mp4'
30
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: VideoTranscodingProfilesManager.Instance.getAvailableEncoders(),
45 profile: CONFIG.TRANSCODING.PROFILE,
46
47 resolution: inputVideoFile.resolution,
48
49 job
50 }
51
52 // Could be very long!
53 await transcode(transcodeOptions)
54
55 try {
56 await remove(videoInputPath)
57
58 // Important to do this before getVideoFilename() to take in account the new filename
59 inputVideoFile.extname = newExtname
60 inputVideoFile.filename = generateVideoFilename(video, false, inputVideoFile.resolution, newExtname)
61
62 const videoOutputPath = getVideoFilePath(video, inputVideoFile)
63
64 await onWebTorrentVideoFileTranscoding(video, inputVideoFile, videoTranscodedPath, videoOutputPath)
65
66 return transcodeType
67 } catch (err) {
68 // Auto destruction...
69 video.destroy().catch(err => logger.error('Cannot destruct video after transcoding failure.', { err }))
70
71 throw err
72 }
73 }
74
75 // Transcode the original video file to a lower resolution.
76 async function transcodeNewWebTorrentResolution (video: MVideoFullLight, resolution: VideoResolution, isPortrait: boolean, job: Job) {
77 const transcodeDirectory = CONFIG.STORAGE.TMP_DIR
78 const extname = '.mp4'
79
80 // We are sure it's x264 in mp4 because optimizeOriginalVideofile was already executed
81 const videoInputPath = getVideoFilePath(video, video.getMaxQualityFile())
82
83 const newVideoFile = new VideoFileModel({
84 resolution,
85 extname,
86 filename: generateVideoFilename(video, false, resolution, extname),
87 size: 0,
88 videoId: video.id
89 })
90
91 const videoOutputPath = getVideoFilePath(video, newVideoFile)
92 const videoTranscodedPath = join(transcodeDirectory, newVideoFile.filename)
93
94 const transcodeOptions = resolution === VideoResolution.H_NOVIDEO
95 ? {
96 type: 'only-audio' as 'only-audio',
97
98 inputPath: videoInputPath,
99 outputPath: videoTranscodedPath,
100
101 availableEncoders: VideoTranscodingProfilesManager.Instance.getAvailableEncoders(),
102 profile: CONFIG.TRANSCODING.PROFILE,
103
104 resolution,
105
106 job
107 }
108 : {
109 type: 'video' as 'video',
110 inputPath: videoInputPath,
111 outputPath: videoTranscodedPath,
112
113 availableEncoders: VideoTranscodingProfilesManager.Instance.getAvailableEncoders(),
114 profile: CONFIG.TRANSCODING.PROFILE,
115
116 resolution,
117 isPortraitMode: isPortrait,
118
119 job
120 }
121
122 await transcode(transcodeOptions)
123
124 return onWebTorrentVideoFileTranscoding(video, newVideoFile, videoTranscodedPath, videoOutputPath)
125 }
126
127 // Merge an image with an audio file to create a video
128 async function mergeAudioVideofile (video: MVideoFullLight, resolution: VideoResolution, job: Job) {
129 const transcodeDirectory = CONFIG.STORAGE.TMP_DIR
130 const newExtname = '.mp4'
131
132 const inputVideoFile = video.getMinQualityFile()
133
134 const audioInputPath = getVideoFilePath(video, inputVideoFile)
135 const videoTranscodedPath = join(transcodeDirectory, video.id + '-transcoded' + newExtname)
136
137 // If the user updates the video preview during transcoding
138 const previewPath = video.getPreview().getPath()
139 const tmpPreviewPath = join(CONFIG.STORAGE.TMP_DIR, basename(previewPath))
140 await copyFile(previewPath, tmpPreviewPath)
141
142 const transcodeOptions = {
143 type: 'merge-audio' as 'merge-audio',
144
145 inputPath: tmpPreviewPath,
146 outputPath: videoTranscodedPath,
147
148 availableEncoders: VideoTranscodingProfilesManager.Instance.getAvailableEncoders(),
149 profile: CONFIG.TRANSCODING.PROFILE,
150
151 audioPath: audioInputPath,
152 resolution,
153
154 job
155 }
156
157 try {
158 await transcode(transcodeOptions)
159
160 await remove(audioInputPath)
161 await remove(tmpPreviewPath)
162 } catch (err) {
163 await remove(tmpPreviewPath)
164 throw err
165 }
166
167 // Important to do this before getVideoFilename() to take in account the new file extension
168 inputVideoFile.extname = newExtname
169
170 const videoOutputPath = getVideoFilePath(video, inputVideoFile)
171 // ffmpeg generated a new video file, so update the video duration
172 // See https://trac.ffmpeg.org/ticket/5456
173 video.duration = await getDurationFromVideoFile(videoTranscodedPath)
174 await video.save()
175
176 return onWebTorrentVideoFileTranscoding(video, inputVideoFile, videoTranscodedPath, videoOutputPath)
177 }
178
179 // Concat TS segments from a live video to a fragmented mp4 HLS playlist
180 async function generateHlsPlaylistResolutionFromTS (options: {
181 video: MVideoFullLight
182 concatenatedTsFilePath: string
183 resolution: VideoResolution
184 isPortraitMode: boolean
185 isAAC: boolean
186 }) {
187 return generateHlsPlaylistCommon({
188 video: options.video,
189 resolution: options.resolution,
190 isPortraitMode: options.isPortraitMode,
191 inputPath: options.concatenatedTsFilePath,
192 type: 'hls-from-ts' as 'hls-from-ts',
193 isAAC: options.isAAC
194 })
195 }
196
197 // Generate an HLS playlist from an input file, and update the master playlist
198 function generateHlsPlaylistResolution (options: {
199 video: MVideoFullLight
200 videoInputPath: string
201 resolution: VideoResolution
202 copyCodecs: boolean
203 isPortraitMode: boolean
204 job?: Job
205 }) {
206 return generateHlsPlaylistCommon({
207 video: options.video,
208 resolution: options.resolution,
209 copyCodecs: options.copyCodecs,
210 isPortraitMode: options.isPortraitMode,
211 inputPath: options.videoInputPath,
212 type: 'hls' as 'hls',
213 job: options.job
214 })
215 }
216
217 function getEnabledResolutions (type: 'vod' | 'live') {
218 const transcoding = type === 'vod'
219 ? CONFIG.TRANSCODING
220 : CONFIG.LIVE.TRANSCODING
221
222 return Object.keys(transcoding.RESOLUTIONS)
223 .filter(key => transcoding.ENABLED && transcoding.RESOLUTIONS[key] === true)
224 .map(r => parseInt(r, 10))
225 }
226
227 // ---------------------------------------------------------------------------
228
229 export {
230 generateHlsPlaylistResolution,
231 generateHlsPlaylistResolutionFromTS,
232 optimizeOriginalVideofile,
233 transcodeNewWebTorrentResolution,
234 mergeAudioVideofile,
235 getEnabledResolutions
236 }
237
238 // ---------------------------------------------------------------------------
239
240 async function onWebTorrentVideoFileTranscoding (
241 video: MVideoFullLight,
242 videoFile: MVideoFile,
243 transcodingPath: string,
244 outputPath: string
245 ) {
246 const stats = await stat(transcodingPath)
247 const fps = await getVideoFileFPS(transcodingPath)
248 const metadata = await getMetadataFromFile(transcodingPath)
249
250 await move(transcodingPath, outputPath, { overwrite: true })
251
252 videoFile.size = stats.size
253 videoFile.fps = fps
254 videoFile.metadata = metadata
255
256 await createTorrentAndSetInfoHash(video, video, videoFile)
257
258 await VideoFileModel.customUpsert(videoFile, 'video', undefined)
259 video.VideoFiles = await video.$get('VideoFiles')
260
261 return video
262 }
263
264 async function generateHlsPlaylistCommon (options: {
265 type: 'hls' | 'hls-from-ts'
266 video: MVideoFullLight
267 inputPath: string
268 resolution: VideoResolution
269 copyCodecs?: boolean
270 isAAC?: boolean
271 isPortraitMode: boolean
272
273 job?: Job
274 }) {
275 const { type, video, inputPath, resolution, copyCodecs, isPortraitMode, isAAC, job } = options
276 const transcodeDirectory = CONFIG.STORAGE.TMP_DIR
277
278 const videoTranscodedBasePath = join(transcodeDirectory, type)
279 await ensureDir(videoTranscodedBasePath)
280
281 const videoFilename = generateVideoStreamingPlaylistName(video.uuid, resolution)
282 const playlistFilename = VideoStreamingPlaylistModel.getHlsPlaylistFilename(resolution)
283 const playlistFileTranscodePath = join(videoTranscodedBasePath, playlistFilename)
284
285 const transcodeOptions = {
286 type,
287
288 inputPath,
289 outputPath: playlistFileTranscodePath,
290
291 availableEncoders: VideoTranscodingProfilesManager.Instance.getAvailableEncoders(),
292 profile: CONFIG.TRANSCODING.PROFILE,
293
294 resolution,
295 copyCodecs,
296 isPortraitMode,
297
298 isAAC,
299
300 hlsPlaylist: {
301 videoFilename
302 },
303
304 job
305 }
306
307 await transcode(transcodeOptions)
308
309 const playlistUrl = WEBSERVER.URL + VideoStreamingPlaylistModel.getHlsMasterPlaylistStaticPath(video.uuid)
310
311 // Create or update the playlist
312 const [ videoStreamingPlaylist ] = await VideoStreamingPlaylistModel.upsert({
313 videoId: video.id,
314 playlistUrl,
315 segmentsSha256Url: WEBSERVER.URL + VideoStreamingPlaylistModel.getHlsSha256SegmentsStaticPath(video.uuid, video.isLive),
316 p2pMediaLoaderInfohashes: [],
317 p2pMediaLoaderPeerVersion: P2P_MEDIA_LOADER_PEER_VERSION,
318
319 type: VideoStreamingPlaylistType.HLS
320 }, { returning: true }) as [ MStreamingPlaylistFilesVideo, boolean ]
321 videoStreamingPlaylist.Video = video
322
323 // Build the new playlist file
324 const extname = extnameUtil(videoFilename)
325 const newVideoFile = new VideoFileModel({
326 resolution,
327 extname,
328 size: 0,
329 filename: generateVideoFilename(video, true, resolution, extname),
330 fps: -1,
331 videoStreamingPlaylistId: videoStreamingPlaylist.id
332 })
333
334 const videoFilePath = getVideoFilePath(videoStreamingPlaylist, newVideoFile)
335
336 // Move files from tmp transcoded directory to the appropriate place
337 const baseHlsDirectory = join(HLS_STREAMING_PLAYLIST_DIRECTORY, video.uuid)
338 await ensureDir(baseHlsDirectory)
339
340 // Move playlist file
341 const playlistPath = join(baseHlsDirectory, playlistFilename)
342 await move(playlistFileTranscodePath, playlistPath, { overwrite: true })
343 // Move video file
344 await move(join(videoTranscodedBasePath, videoFilename), videoFilePath, { overwrite: true })
345
346 const stats = await stat(videoFilePath)
347
348 newVideoFile.size = stats.size
349 newVideoFile.fps = await getVideoFileFPS(videoFilePath)
350 newVideoFile.metadata = await getMetadataFromFile(videoFilePath)
351
352 await createTorrentAndSetInfoHash(videoStreamingPlaylist, video, newVideoFile)
353
354 await VideoFileModel.customUpsert(newVideoFile, 'streaming-playlist', undefined)
355 videoStreamingPlaylist.VideoFiles = await videoStreamingPlaylist.$get('VideoFiles')
356
357 videoStreamingPlaylist.p2pMediaLoaderInfohashes = VideoStreamingPlaylistModel.buildP2PMediaLoaderInfoHashes(
358 playlistUrl, videoStreamingPlaylist.VideoFiles
359 )
360 await videoStreamingPlaylist.save()
361
362 video.setHLSPlaylist(videoStreamingPlaylist)
363
364 await updateMasterHLSPlaylist(video)
365 await updateSha256VODSegments(video)
366
367 return playlistPath
368 }