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