]>
Commit | Line | Data |
---|---|---|
053aed43 | 1 | import { copyFile, ensureDir, move, remove, stat } from 'fs-extra' |
d7a25329 | 2 | import { basename, extname as extnameUtil, join } from 'path' |
053aed43 C |
3 | import { createTorrentAndSetInfoHash } from '@server/helpers/webtorrent' |
4 | import { MStreamingPlaylistFilesVideo, MVideoFile, MVideoWithAllFiles, MVideoWithFile } from '@server/types/models' | |
9252a33d | 5 | import { getTargetBitrate, VideoResolution } from '../../shared/models/videos' |
053aed43 | 6 | import { VideoStreamingPlaylistType } from '../../shared/models/videos/video-streaming-playlist.type' |
9252a33d C |
7 | import { AvailableEncoders, EncoderOptionsBuilder, transcode, TranscodeOptions, TranscodeOptionsType } from '../helpers/ffmpeg-utils' |
8 | import { | |
9 | canDoQuickTranscode, | |
10 | getAudioStream, | |
11 | getDurationFromVideoFile, | |
12 | getMaxAudioBitrate, | |
13 | getMetadataFromFile, | |
14 | getVideoFileBitrate, | |
15 | getVideoFileFPS | |
16 | } from '../helpers/ffprobe-utils' | |
098eb377 | 17 | import { logger } from '../helpers/logger' |
053aed43 | 18 | import { CONFIG } from '../initializers/config' |
9252a33d C |
19 | import { |
20 | HLS_STREAMING_PLAYLIST_DIRECTORY, | |
21 | P2P_MEDIA_LOADER_PEER_VERSION, | |
22 | VIDEO_TRANSCODING_FPS, | |
23 | WEBSERVER | |
24 | } from '../initializers/constants' | |
098eb377 | 25 | import { VideoFileModel } from '../models/video/video-file' |
09209296 | 26 | import { VideoStreamingPlaylistModel } from '../models/video/video-streaming-playlist' |
053aed43 | 27 | import { updateMasterHLSPlaylist, updateSha256VODSegments } from './hls' |
d7a25329 | 28 | import { generateVideoStreamingPlaylistName, getVideoFilename, getVideoFilePath } from './video-paths' |
098eb377 | 29 | |
658a47ab FA |
30 | /** |
31 | * Optimize the original video file and replace it. The resolution is not changed. | |
32 | */ | |
d7a25329 | 33 | async function optimizeOriginalVideofile (video: MVideoWithFile, inputVideoFileArg?: MVideoFile) { |
2fbd5e25 | 34 | const transcodeDirectory = CONFIG.STORAGE.TMP_DIR |
098eb377 | 35 | const newExtname = '.mp4' |
9f1ddd24 | 36 | |
d7a25329 C |
37 | const inputVideoFile = inputVideoFileArg || video.getMaxQualityFile() |
38 | const videoInputPath = getVideoFilePath(video, inputVideoFile) | |
2fbd5e25 | 39 | const videoTranscodedPath = join(transcodeDirectory, video.id + '-transcoded' + newExtname) |
098eb377 | 40 | |
536598cf C |
41 | const transcodeType: TranscodeOptionsType = await canDoQuickTranscode(videoInputPath) |
42 | ? 'quick-transcode' | |
43 | : 'video' | |
5ba49f26 | 44 | |
536598cf | 45 | const transcodeOptions: TranscodeOptions = { |
d7a25329 | 46 | type: transcodeType, |
9252a33d | 47 | |
098eb377 | 48 | inputPath: videoInputPath, |
09209296 | 49 | outputPath: videoTranscodedPath, |
9252a33d C |
50 | |
51 | availableEncoders, | |
52 | profile: 'default', | |
53 | ||
536598cf | 54 | resolution: inputVideoFile.resolution |
098eb377 C |
55 | } |
56 | ||
57 | // Could be very long! | |
58 | await transcode(transcodeOptions) | |
59 | ||
60 | try { | |
61 | await remove(videoInputPath) | |
62 | ||
63 | // Important to do this before getVideoFilename() to take in account the new file extension | |
536598cf | 64 | inputVideoFile.extname = newExtname |
2fbd5e25 | 65 | |
d7a25329 | 66 | const videoOutputPath = getVideoFilePath(video, inputVideoFile) |
098eb377 | 67 | |
536598cf | 68 | await onVideoFileTranscoding(video, inputVideoFile, videoTranscodedPath, videoOutputPath) |
098eb377 C |
69 | } catch (err) { |
70 | // Auto destruction... | |
71 | video.destroy().catch(err => logger.error('Cannot destruct video after transcoding failure.', { err })) | |
72 | ||
73 | throw err | |
74 | } | |
75 | } | |
76 | ||
658a47ab FA |
77 | /** |
78 | * Transcode the original video file to a lower resolution. | |
79 | */ | |
d7a25329 | 80 | async function transcodeNewResolution (video: MVideoWithFile, resolution: VideoResolution, isPortrait: boolean) { |
2fbd5e25 | 81 | const transcodeDirectory = CONFIG.STORAGE.TMP_DIR |
098eb377 C |
82 | const extname = '.mp4' |
83 | ||
84 | // We are sure it's x264 in mp4 because optimizeOriginalVideofile was already executed | |
d7a25329 | 85 | const videoInputPath = getVideoFilePath(video, video.getMaxQualityFile()) |
098eb377 C |
86 | |
87 | const newVideoFile = new VideoFileModel({ | |
88 | resolution, | |
89 | extname, | |
90 | size: 0, | |
91 | videoId: video.id | |
92 | }) | |
d7a25329 C |
93 | const videoOutputPath = getVideoFilePath(video, newVideoFile) |
94 | const videoTranscodedPath = join(transcodeDirectory, getVideoFilename(video, newVideoFile)) | |
098eb377 | 95 | |
5c7d6508 | 96 | const transcodeOptions = resolution === VideoResolution.H_NOVIDEO |
97 | ? { | |
3a149e9f | 98 | type: 'only-audio' as 'only-audio', |
9252a33d | 99 | |
3a149e9f C |
100 | inputPath: videoInputPath, |
101 | outputPath: videoTranscodedPath, | |
9252a33d C |
102 | |
103 | availableEncoders, | |
104 | profile: 'default', | |
105 | ||
3a149e9f C |
106 | resolution |
107 | } | |
5c7d6508 | 108 | : { |
3a149e9f C |
109 | type: 'video' as 'video', |
110 | inputPath: videoInputPath, | |
111 | outputPath: videoTranscodedPath, | |
9252a33d C |
112 | |
113 | availableEncoders, | |
114 | profile: 'default', | |
115 | ||
3a149e9f C |
116 | resolution, |
117 | isPortraitMode: isPortrait | |
118 | } | |
098eb377 C |
119 | |
120 | await transcode(transcodeOptions) | |
121 | ||
536598cf C |
122 | return onVideoFileTranscoding(video, newVideoFile, videoTranscodedPath, videoOutputPath) |
123 | } | |
124 | ||
d7a25329 | 125 | async function mergeAudioVideofile (video: MVideoWithAllFiles, resolution: VideoResolution) { |
536598cf C |
126 | const transcodeDirectory = CONFIG.STORAGE.TMP_DIR |
127 | const newExtname = '.mp4' | |
128 | ||
92e0f42e | 129 | const inputVideoFile = video.getMinQualityFile() |
2fbd5e25 | 130 | |
d7a25329 | 131 | const audioInputPath = getVideoFilePath(video, inputVideoFile) |
536598cf | 132 | const videoTranscodedPath = join(transcodeDirectory, video.id + '-transcoded' + newExtname) |
098eb377 | 133 | |
eba06469 C |
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 | ||
536598cf C |
139 | const transcodeOptions = { |
140 | type: 'merge-audio' as 'merge-audio', | |
9252a33d | 141 | |
eba06469 | 142 | inputPath: tmpPreviewPath, |
536598cf | 143 | outputPath: videoTranscodedPath, |
9252a33d C |
144 | |
145 | availableEncoders, | |
146 | profile: 'default', | |
147 | ||
536598cf C |
148 | audioPath: audioInputPath, |
149 | resolution | |
150 | } | |
098eb377 | 151 | |
eba06469 C |
152 | try { |
153 | await transcode(transcodeOptions) | |
098eb377 | 154 | |
eba06469 C |
155 | await remove(audioInputPath) |
156 | await remove(tmpPreviewPath) | |
157 | } catch (err) { | |
158 | await remove(tmpPreviewPath) | |
159 | throw err | |
160 | } | |
098eb377 | 161 | |
536598cf C |
162 | // Important to do this before getVideoFilename() to take in account the new file extension |
163 | inputVideoFile.extname = newExtname | |
164 | ||
d7a25329 | 165 | const videoOutputPath = getVideoFilePath(video, inputVideoFile) |
eba06469 C |
166 | // ffmpeg generated a new video file, so update the video duration |
167 | // See https://trac.ffmpeg.org/ticket/5456 | |
168 | video.duration = await getDurationFromVideoFile(videoTranscodedPath) | |
169 | await video.save() | |
536598cf C |
170 | |
171 | return onVideoFileTranscoding(video, inputVideoFile, videoTranscodedPath, videoOutputPath) | |
098eb377 C |
172 | } |
173 | ||
b5b68755 C |
174 | async function generateHlsPlaylist (options: { |
175 | video: MVideoWithFile | |
176 | videoInputPath: string | |
177 | resolution: VideoResolution | |
178 | copyCodecs: boolean | |
179 | isPortraitMode: boolean | |
180 | }) { | |
181 | const { video, videoInputPath, resolution, copyCodecs, isPortraitMode } = options | |
182 | ||
9c6ca37f C |
183 | const baseHlsDirectory = join(HLS_STREAMING_PLAYLIST_DIRECTORY, video.uuid) |
184 | await ensureDir(join(HLS_STREAMING_PLAYLIST_DIRECTORY, video.uuid)) | |
09209296 | 185 | |
09209296 | 186 | const outputPath = join(baseHlsDirectory, VideoStreamingPlaylistModel.getHlsPlaylistFilename(resolution)) |
d7a25329 | 187 | const videoFilename = generateVideoStreamingPlaylistName(video.uuid, resolution) |
09209296 C |
188 | |
189 | const transcodeOptions = { | |
536598cf | 190 | type: 'hls' as 'hls', |
9252a33d | 191 | |
09209296 C |
192 | inputPath: videoInputPath, |
193 | outputPath, | |
9252a33d C |
194 | |
195 | availableEncoders, | |
196 | profile: 'default', | |
197 | ||
09209296 | 198 | resolution, |
d7a25329 | 199 | copyCodecs, |
09209296 | 200 | isPortraitMode, |
4c280004 C |
201 | |
202 | hlsPlaylist: { | |
d7a25329 | 203 | videoFilename |
4c280004 | 204 | } |
09209296 C |
205 | } |
206 | ||
d7a25329 | 207 | await transcode(transcodeOptions) |
09209296 | 208 | |
6dd9de95 | 209 | const playlistUrl = WEBSERVER.URL + VideoStreamingPlaylistModel.getHlsMasterPlaylistStaticPath(video.uuid) |
09209296 | 210 | |
d7a25329 | 211 | const [ videoStreamingPlaylist ] = await VideoStreamingPlaylistModel.upsert({ |
09209296 C |
212 | videoId: video.id, |
213 | playlistUrl, | |
c6c0fa6c | 214 | segmentsSha256Url: WEBSERVER.URL + VideoStreamingPlaylistModel.getHlsSha256SegmentsStaticPath(video.uuid, video.isLive), |
b5b68755 | 215 | p2pMediaLoaderInfohashes: [], |
594d0c6a | 216 | p2pMediaLoaderPeerVersion: P2P_MEDIA_LOADER_PEER_VERSION, |
09209296 C |
217 | |
218 | type: VideoStreamingPlaylistType.HLS | |
d7a25329 C |
219 | }, { returning: true }) as [ MStreamingPlaylistFilesVideo, boolean ] |
220 | videoStreamingPlaylist.Video = video | |
221 | ||
222 | const newVideoFile = new VideoFileModel({ | |
223 | resolution, | |
224 | extname: extnameUtil(videoFilename), | |
225 | size: 0, | |
226 | fps: -1, | |
227 | videoStreamingPlaylistId: videoStreamingPlaylist.id | |
09209296 | 228 | }) |
d7a25329 C |
229 | |
230 | const videoFilePath = getVideoFilePath(videoStreamingPlaylist, newVideoFile) | |
231 | const stats = await stat(videoFilePath) | |
232 | ||
233 | newVideoFile.size = stats.size | |
234 | newVideoFile.fps = await getVideoFileFPS(videoFilePath) | |
8319d6ae | 235 | newVideoFile.metadata = await getMetadataFromFile(videoFilePath) |
d7a25329 C |
236 | |
237 | await createTorrentAndSetInfoHash(videoStreamingPlaylist, newVideoFile) | |
238 | ||
c547bbf9 | 239 | await VideoFileModel.customUpsert(newVideoFile, 'streaming-playlist', undefined) |
e6122097 | 240 | videoStreamingPlaylist.VideoFiles = await videoStreamingPlaylist.$get('VideoFiles') |
d7a25329 | 241 | |
b5b68755 C |
242 | videoStreamingPlaylist.p2pMediaLoaderInfohashes = VideoStreamingPlaylistModel.buildP2PMediaLoaderInfoHashes( |
243 | playlistUrl, videoStreamingPlaylist.VideoFiles | |
244 | ) | |
245 | await videoStreamingPlaylist.save() | |
246 | ||
d7a25329 C |
247 | video.setHLSPlaylist(videoStreamingPlaylist) |
248 | ||
249 | await updateMasterHLSPlaylist(video) | |
c6c0fa6c | 250 | await updateSha256VODSegments(video) |
d7a25329 C |
251 | |
252 | return video | |
09209296 C |
253 | } |
254 | ||
9252a33d C |
255 | // --------------------------------------------------------------------------- |
256 | // Available encoders profiles | |
257 | // --------------------------------------------------------------------------- | |
258 | ||
259 | const defaultX264OptionsBuilder: EncoderOptionsBuilder = async ({ input, resolution, fps }) => { | |
260 | if (!fps) return { outputOptions: [] } | |
261 | ||
262 | let targetBitrate = getTargetBitrate(resolution, fps, VIDEO_TRANSCODING_FPS) | |
263 | ||
264 | // Don't transcode to an higher bitrate than the original file | |
265 | const fileBitrate = await getVideoFileBitrate(input) | |
266 | targetBitrate = Math.min(targetBitrate, fileBitrate) | |
267 | ||
268 | return { | |
269 | outputOptions: [ | |
270 | // Constrained Encoding (VBV) | |
271 | // https://slhck.info/video/2017/03/01/rate-control.html | |
272 | // https://trac.ffmpeg.org/wiki/Limiting%20the%20output%20bitrate | |
273 | `-maxrate ${targetBitrate}`, `-bufsize ${targetBitrate * 2}` | |
274 | ] | |
275 | } | |
276 | } | |
277 | ||
278 | const defaultAACOptionsBuilder: EncoderOptionsBuilder = async ({ input }) => { | |
279 | const parsedAudio = await getAudioStream(input) | |
280 | ||
281 | // we try to reduce the ceiling bitrate by making rough matches of bitrates | |
282 | // of course this is far from perfect, but it might save some space in the end | |
283 | ||
284 | const audioCodecName = parsedAudio.audioStream['codec_name'] | |
285 | ||
286 | const bitrate = getMaxAudioBitrate(audioCodecName, parsedAudio.bitrate) | |
287 | ||
288 | if (bitrate !== undefined && bitrate !== -1) { | |
289 | return { outputOptions: [ '-b:a', bitrate + 'k' ] } | |
290 | } | |
291 | ||
292 | return { outputOptions: [] } | |
293 | } | |
294 | ||
295 | const defaultLibFDKAACOptionsBuilder: EncoderOptionsBuilder = () => { | |
296 | return { outputOptions: [ '-aq', '5' ] } | |
297 | } | |
298 | ||
299 | const availableEncoders: AvailableEncoders = { | |
300 | vod: { | |
301 | libx264: { | |
302 | default: defaultX264OptionsBuilder | |
303 | }, | |
304 | aac: { | |
305 | default: defaultAACOptionsBuilder | |
306 | }, | |
307 | libfdkAAC: { | |
308 | default: defaultLibFDKAACOptionsBuilder | |
309 | } | |
310 | }, | |
311 | live: { | |
312 | libx264: { | |
313 | default: defaultX264OptionsBuilder | |
314 | }, | |
315 | aac: { | |
316 | default: defaultAACOptionsBuilder | |
317 | }, | |
318 | libfdkAAC: { | |
319 | default: defaultLibFDKAACOptionsBuilder | |
320 | } | |
321 | } | |
322 | } | |
323 | ||
536598cf C |
324 | // --------------------------------------------------------------------------- |
325 | ||
098eb377 | 326 | export { |
09209296 | 327 | generateHlsPlaylist, |
d7a25329 C |
328 | optimizeOriginalVideofile, |
329 | transcodeNewResolution, | |
536598cf C |
330 | mergeAudioVideofile |
331 | } | |
332 | ||
333 | // --------------------------------------------------------------------------- | |
334 | ||
453e83ea | 335 | async function onVideoFileTranscoding (video: MVideoWithFile, videoFile: MVideoFile, transcodingPath: string, outputPath: string) { |
536598cf C |
336 | const stats = await stat(transcodingPath) |
337 | const fps = await getVideoFileFPS(transcodingPath) | |
8319d6ae | 338 | const metadata = await getMetadataFromFile(transcodingPath) |
536598cf | 339 | |
fb0f7f82 | 340 | await move(transcodingPath, outputPath, { overwrite: true }) |
536598cf | 341 | |
453e83ea C |
342 | videoFile.size = stats.size |
343 | videoFile.fps = fps | |
8319d6ae | 344 | videoFile.metadata = metadata |
536598cf | 345 | |
d7a25329 | 346 | await createTorrentAndSetInfoHash(video, videoFile) |
536598cf | 347 | |
fb0f7f82 C |
348 | await VideoFileModel.customUpsert(videoFile, 'video', undefined) |
349 | video.VideoFiles = await video.$get('VideoFiles') | |
536598cf C |
350 | |
351 | return video | |
098eb377 | 352 | } |