]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/lib/video-transcoding.ts
Add audio-only option to transcoders and player
[github/Chocobozzz/PeerTube.git] / server / lib / video-transcoding.ts
CommitLineData
7ed2c1a4 1import { HLS_STREAMING_PLAYLIST_DIRECTORY, P2P_MEDIA_LOADER_PEER_VERSION, WEBSERVER } from '../initializers/constants'
d7a25329 2import { basename, extname as extnameUtil, join } from 'path'
eba06469
C
3import {
4 canDoQuickTranscode,
5 getDurationFromVideoFile,
6 getVideoFileFPS,
7 transcode,
8 TranscodeOptions,
9 TranscodeOptionsType
10} from '../helpers/ffmpeg-utils'
11import { copyFile, ensureDir, move, remove, stat } from 'fs-extra'
098eb377
C
12import { logger } from '../helpers/logger'
13import { VideoResolution } from '../../shared/models/videos'
14import { VideoFileModel } from '../models/video/video-file'
09209296
C
15import { updateMasterHLSPlaylist, updateSha256Segments } from './hls'
16import { VideoStreamingPlaylistModel } from '../models/video/video-streaming-playlist'
17import { VideoStreamingPlaylistType } from '../../shared/models/videos/video-streaming-playlist.type'
6dd9de95 18import { CONFIG } from '../initializers/config'
d7a25329
C
19import { MStreamingPlaylistFilesVideo, MVideoFile, MVideoWithAllFiles, MVideoWithFile } from '@server/typings/models'
20import { createTorrentAndSetInfoHash } from '@server/helpers/webtorrent'
21import { generateVideoStreamingPlaylistName, getVideoFilename, getVideoFilePath } from './video-paths'
098eb377 22
658a47ab
FA
23/**
24 * Optimize the original video file and replace it. The resolution is not changed.
25 */
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,
098eb377 40 inputPath: videoInputPath,
09209296 41 outputPath: videoTranscodedPath,
536598cf 42 resolution: inputVideoFile.resolution
098eb377
C
43 }
44
45 // Could be very long!
46 await transcode(transcodeOptions)
47
48 try {
49 await remove(videoInputPath)
50
51 // Important to do this before getVideoFilename() to take in account the new file extension
536598cf 52 inputVideoFile.extname = newExtname
2fbd5e25 53
d7a25329 54 const videoOutputPath = getVideoFilePath(video, inputVideoFile)
098eb377 55
536598cf 56 await onVideoFileTranscoding(video, inputVideoFile, videoTranscodedPath, videoOutputPath)
098eb377
C
57 } catch (err) {
58 // Auto destruction...
59 video.destroy().catch(err => logger.error('Cannot destruct video after transcoding failure.', { err }))
60
61 throw err
62 }
63}
64
658a47ab
FA
65/**
66 * Transcode the original video file to a lower resolution.
67 */
d7a25329 68async function transcodeNewResolution (video: MVideoWithFile, resolution: VideoResolution, isPortrait: boolean) {
2fbd5e25 69 const transcodeDirectory = CONFIG.STORAGE.TMP_DIR
098eb377
C
70 const extname = '.mp4'
71
72 // We are sure it's x264 in mp4 because optimizeOriginalVideofile was already executed
d7a25329 73 const videoInputPath = getVideoFilePath(video, video.getMaxQualityFile())
098eb377
C
74
75 const newVideoFile = new VideoFileModel({
76 resolution,
77 extname,
78 size: 0,
79 videoId: video.id
80 })
d7a25329
C
81 const videoOutputPath = getVideoFilePath(video, newVideoFile)
82 const videoTranscodedPath = join(transcodeDirectory, getVideoFilename(video, newVideoFile))
098eb377 83
5c7d6508 84 const transcodeOptions = resolution === VideoResolution.H_NOVIDEO
85 ? {
86 type: 'split-audio' as 'split-audio',
87 inputPath: videoInputPath,
88 outputPath: videoTranscodedPath,
89 resolution,
90 }
91 : {
92 type: 'video' as 'video',
93 inputPath: videoInputPath,
94 outputPath: videoTranscodedPath,
95 resolution,
96 isPortraitMode: isPortrait
97 }
98
99 await transcode(transcodeOptions)
100
101 return onVideoFileTranscoding(video, newVideoFile, videoTranscodedPath, videoOutputPath)
102}
103
104/**
105 * Extract audio into a separate audio-only mp4.
106 */
107async function splitAudioFile (video: MVideoWithFile) {
108 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
109 const transcodeDirectory = CONFIG.STORAGE.TMP_DIR
110 const extname = '.mp4'
111 const resolution = VideoResolution.H_NOVIDEO
112
113 // We are sure it's x264 in mp4 because optimizeOriginalVideofile was already executed
114 const videoInputPath = join(videosDirectory, video.getVideoFilename(video.getOriginalFile()))
115
116 const newVideoFile = new VideoFileModel({
117 resolution,
118 extname,
119 size: 0,
120 videoId: video.id
121 })
122 const videoOutputPath = join(CONFIG.STORAGE.VIDEOS_DIR, video.getVideoFilename(newVideoFile))
123 const videoTranscodedPath = join(transcodeDirectory, video.getVideoFilename(newVideoFile))
124
098eb377 125 const transcodeOptions = {
5c7d6508 126 type: 'split-audio' as 'split-audio',
098eb377 127 inputPath: videoInputPath,
2fbd5e25 128 outputPath: videoTranscodedPath,
5c7d6508 129 resolution
098eb377
C
130 }
131
132 await transcode(transcodeOptions)
133
536598cf
C
134 return onVideoFileTranscoding(video, newVideoFile, videoTranscodedPath, videoOutputPath)
135}
136
d7a25329 137async function mergeAudioVideofile (video: MVideoWithAllFiles, resolution: VideoResolution) {
536598cf
C
138 const transcodeDirectory = CONFIG.STORAGE.TMP_DIR
139 const newExtname = '.mp4'
140
d7a25329 141 const inputVideoFile = video.getMaxQualityFile()
2fbd5e25 142
d7a25329 143 const audioInputPath = getVideoFilePath(video, inputVideoFile)
536598cf 144 const videoTranscodedPath = join(transcodeDirectory, video.id + '-transcoded' + newExtname)
098eb377 145
eba06469
C
146 // If the user updates the video preview during transcoding
147 const previewPath = video.getPreview().getPath()
148 const tmpPreviewPath = join(CONFIG.STORAGE.TMP_DIR, basename(previewPath))
149 await copyFile(previewPath, tmpPreviewPath)
150
536598cf
C
151 const transcodeOptions = {
152 type: 'merge-audio' as 'merge-audio',
eba06469 153 inputPath: tmpPreviewPath,
536598cf
C
154 outputPath: videoTranscodedPath,
155 audioPath: audioInputPath,
156 resolution
157 }
098eb377 158
eba06469
C
159 try {
160 await transcode(transcodeOptions)
098eb377 161
eba06469
C
162 await remove(audioInputPath)
163 await remove(tmpPreviewPath)
164 } catch (err) {
165 await remove(tmpPreviewPath)
166 throw err
167 }
098eb377 168
536598cf
C
169 // Important to do this before getVideoFilename() to take in account the new file extension
170 inputVideoFile.extname = newExtname
171
d7a25329 172 const videoOutputPath = getVideoFilePath(video, inputVideoFile)
eba06469
C
173 // ffmpeg generated a new video file, so update the video duration
174 // See https://trac.ffmpeg.org/ticket/5456
175 video.duration = await getDurationFromVideoFile(videoTranscodedPath)
176 await video.save()
536598cf
C
177
178 return onVideoFileTranscoding(video, inputVideoFile, videoTranscodedPath, videoOutputPath)
098eb377
C
179}
180
d7a25329 181async function generateHlsPlaylist (video: MVideoWithFile, resolution: VideoResolution, copyCodecs: boolean, isPortraitMode: boolean) {
9c6ca37f
C
182 const baseHlsDirectory = join(HLS_STREAMING_PLAYLIST_DIRECTORY, video.uuid)
183 await ensureDir(join(HLS_STREAMING_PLAYLIST_DIRECTORY, video.uuid))
09209296 184
d7a25329
C
185 const videoFileInput = copyCodecs
186 ? video.getWebTorrentFile(resolution)
187 : video.getMaxQualityFile()
188
189 const videoOrStreamingPlaylist = videoFileInput.getVideoOrStreamingPlaylist()
190 const videoInputPath = getVideoFilePath(videoOrStreamingPlaylist, videoFileInput)
191
09209296 192 const outputPath = join(baseHlsDirectory, VideoStreamingPlaylistModel.getHlsPlaylistFilename(resolution))
d7a25329 193 const videoFilename = generateVideoStreamingPlaylistName(video.uuid, resolution)
09209296
C
194
195 const transcodeOptions = {
536598cf 196 type: 'hls' as 'hls',
09209296
C
197 inputPath: videoInputPath,
198 outputPath,
199 resolution,
d7a25329 200 copyCodecs,
09209296 201 isPortraitMode,
4c280004
C
202
203 hlsPlaylist: {
d7a25329 204 videoFilename
4c280004 205 }
09209296
C
206 }
207
d7a25329 208 logger.debug('Will run transcode.', { transcodeOptions })
09209296 209
d7a25329 210 await transcode(transcodeOptions)
09209296 211
6dd9de95 212 const playlistUrl = WEBSERVER.URL + VideoStreamingPlaylistModel.getHlsMasterPlaylistStaticPath(video.uuid)
09209296 213
d7a25329 214 const [ videoStreamingPlaylist ] = await VideoStreamingPlaylistModel.upsert({
09209296
C
215 videoId: video.id,
216 playlistUrl,
6dd9de95 217 segmentsSha256Url: WEBSERVER.URL + VideoStreamingPlaylistModel.getHlsSha256SegmentsStaticPath(video.uuid),
09209296 218 p2pMediaLoaderInfohashes: VideoStreamingPlaylistModel.buildP2PMediaLoaderInfoHashes(playlistUrl, video.VideoFiles),
594d0c6a 219 p2pMediaLoaderPeerVersion: P2P_MEDIA_LOADER_PEER_VERSION,
09209296
C
220
221 type: VideoStreamingPlaylistType.HLS
d7a25329
C
222 }, { returning: true }) as [ MStreamingPlaylistFilesVideo, boolean ]
223 videoStreamingPlaylist.Video = video
224
225 const newVideoFile = new VideoFileModel({
226 resolution,
227 extname: extnameUtil(videoFilename),
228 size: 0,
229 fps: -1,
230 videoStreamingPlaylistId: videoStreamingPlaylist.id
09209296 231 })
d7a25329
C
232
233 const videoFilePath = getVideoFilePath(videoStreamingPlaylist, newVideoFile)
234 const stats = await stat(videoFilePath)
235
236 newVideoFile.size = stats.size
237 newVideoFile.fps = await getVideoFileFPS(videoFilePath)
238
239 await createTorrentAndSetInfoHash(videoStreamingPlaylist, newVideoFile)
240
241 const updatedVideoFile = await newVideoFile.save()
242
243 videoStreamingPlaylist.VideoFiles = await videoStreamingPlaylist.$get('VideoFiles') as VideoFileModel[]
244 videoStreamingPlaylist.VideoFiles.push(updatedVideoFile)
245
246 video.setHLSPlaylist(videoStreamingPlaylist)
247
248 await updateMasterHLSPlaylist(video)
249 await updateSha256Segments(video)
250
251 return video
09209296
C
252}
253
536598cf
C
254// ---------------------------------------------------------------------------
255
098eb377 256export {
09209296 257 generateHlsPlaylist,
d7a25329
C
258 optimizeOriginalVideofile,
259 transcodeNewResolution,
536598cf
C
260 mergeAudioVideofile
261}
262
263// ---------------------------------------------------------------------------
264
453e83ea 265async function onVideoFileTranscoding (video: MVideoWithFile, videoFile: MVideoFile, transcodingPath: string, outputPath: string) {
536598cf
C
266 const stats = await stat(transcodingPath)
267 const fps = await getVideoFileFPS(transcodingPath)
268
269 await move(transcodingPath, outputPath)
270
453e83ea
C
271 videoFile.size = stats.size
272 videoFile.fps = fps
536598cf 273
d7a25329 274 await createTorrentAndSetInfoHash(video, videoFile)
536598cf
C
275
276 const updatedVideoFile = await videoFile.save()
277
278 // Add it if this is a new created file
279 if (video.VideoFiles.some(f => f.id === videoFile.id) === false) {
280 video.VideoFiles.push(updatedVideoFile)
281 }
282
283 return video
098eb377 284}