]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/lib/video-transcoding.ts
Fix audio encoding params
[github/Chocobozzz/PeerTube.git] / server / lib / video-transcoding.ts
CommitLineData
053aed43 1import { copyFile, ensureDir, move, remove, stat } from 'fs-extra'
d7a25329 2import { basename, extname as extnameUtil, join } from 'path'
053aed43
C
3import { createTorrentAndSetInfoHash } from '@server/helpers/webtorrent'
4import { MStreamingPlaylistFilesVideo, MVideoFile, MVideoWithAllFiles, MVideoWithFile } from '@server/types/models'
5a547f69 5import { VideoResolution } from '../../shared/models/videos'
053aed43 6import { VideoStreamingPlaylistType } from '../../shared/models/videos/video-streaming-playlist.type'
5a547f69
C
7import { transcode, TranscodeOptions, TranscodeOptionsType } from '../helpers/ffmpeg-utils'
8import { canDoQuickTranscode, getDurationFromVideoFile, getMetadataFromFile, getVideoFileFPS } from '../helpers/ffprobe-utils'
098eb377 9import { logger } from '../helpers/logger'
053aed43 10import { CONFIG } from '../initializers/config'
5a547f69 11import { HLS_STREAMING_PLAYLIST_DIRECTORY, P2P_MEDIA_LOADER_PEER_VERSION, WEBSERVER } from '../initializers/constants'
098eb377 12import { VideoFileModel } from '../models/video/video-file'
09209296 13import { VideoStreamingPlaylistModel } from '../models/video/video-streaming-playlist'
053aed43 14import { updateMasterHLSPlaylist, updateSha256VODSegments } from './hls'
d7a25329 15import { generateVideoStreamingPlaylistName, getVideoFilename, getVideoFilePath } from './video-paths'
5a547f69 16import { availableEncoders } from './video-transcoding-profiles'
098eb377 17
658a47ab
FA
18/**
19 * Optimize the original video file and replace it. The resolution is not changed.
20 */
d7a25329 21async function optimizeOriginalVideofile (video: MVideoWithFile, inputVideoFileArg?: MVideoFile) {
2fbd5e25 22 const transcodeDirectory = CONFIG.STORAGE.TMP_DIR
098eb377 23 const newExtname = '.mp4'
9f1ddd24 24
d7a25329
C
25 const inputVideoFile = inputVideoFileArg || video.getMaxQualityFile()
26 const videoInputPath = getVideoFilePath(video, inputVideoFile)
2fbd5e25 27 const videoTranscodedPath = join(transcodeDirectory, video.id + '-transcoded' + newExtname)
098eb377 28
536598cf
C
29 const transcodeType: TranscodeOptionsType = await canDoQuickTranscode(videoInputPath)
30 ? 'quick-transcode'
31 : 'video'
5ba49f26 32
536598cf 33 const transcodeOptions: TranscodeOptions = {
d7a25329 34 type: transcodeType,
9252a33d 35
098eb377 36 inputPath: videoInputPath,
09209296 37 outputPath: videoTranscodedPath,
9252a33d
C
38
39 availableEncoders,
40 profile: 'default',
41
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 ? {
3a149e9f 86 type: 'only-audio' as 'only-audio',
9252a33d 87
3a149e9f
C
88 inputPath: videoInputPath,
89 outputPath: videoTranscodedPath,
9252a33d
C
90
91 availableEncoders,
92 profile: 'default',
93
3a149e9f
C
94 resolution
95 }
5c7d6508 96 : {
3a149e9f
C
97 type: 'video' as 'video',
98 inputPath: videoInputPath,
99 outputPath: videoTranscodedPath,
9252a33d
C
100
101 availableEncoders,
102 profile: 'default',
103
3a149e9f
C
104 resolution,
105 isPortraitMode: isPortrait
106 }
098eb377
C
107
108 await transcode(transcodeOptions)
109
536598cf
C
110 return onVideoFileTranscoding(video, newVideoFile, videoTranscodedPath, videoOutputPath)
111}
112
d7a25329 113async function mergeAudioVideofile (video: MVideoWithAllFiles, resolution: VideoResolution) {
536598cf
C
114 const transcodeDirectory = CONFIG.STORAGE.TMP_DIR
115 const newExtname = '.mp4'
116
92e0f42e 117 const inputVideoFile = video.getMinQualityFile()
2fbd5e25 118
d7a25329 119 const audioInputPath = getVideoFilePath(video, inputVideoFile)
536598cf 120 const videoTranscodedPath = join(transcodeDirectory, video.id + '-transcoded' + newExtname)
098eb377 121
eba06469
C
122 // If the user updates the video preview during transcoding
123 const previewPath = video.getPreview().getPath()
124 const tmpPreviewPath = join(CONFIG.STORAGE.TMP_DIR, basename(previewPath))
125 await copyFile(previewPath, tmpPreviewPath)
126
536598cf
C
127 const transcodeOptions = {
128 type: 'merge-audio' as 'merge-audio',
9252a33d 129
eba06469 130 inputPath: tmpPreviewPath,
536598cf 131 outputPath: videoTranscodedPath,
9252a33d
C
132
133 availableEncoders,
134 profile: 'default',
135
536598cf
C
136 audioPath: audioInputPath,
137 resolution
138 }
098eb377 139
eba06469
C
140 try {
141 await transcode(transcodeOptions)
098eb377 142
eba06469
C
143 await remove(audioInputPath)
144 await remove(tmpPreviewPath)
145 } catch (err) {
146 await remove(tmpPreviewPath)
147 throw err
148 }
098eb377 149
536598cf
C
150 // Important to do this before getVideoFilename() to take in account the new file extension
151 inputVideoFile.extname = newExtname
152
d7a25329 153 const videoOutputPath = getVideoFilePath(video, inputVideoFile)
eba06469
C
154 // ffmpeg generated a new video file, so update the video duration
155 // See https://trac.ffmpeg.org/ticket/5456
156 video.duration = await getDurationFromVideoFile(videoTranscodedPath)
157 await video.save()
536598cf
C
158
159 return onVideoFileTranscoding(video, inputVideoFile, videoTranscodedPath, videoOutputPath)
098eb377
C
160}
161
b5b68755
C
162async function generateHlsPlaylist (options: {
163 video: MVideoWithFile
164 videoInputPath: string
165 resolution: VideoResolution
166 copyCodecs: boolean
167 isPortraitMode: boolean
168}) {
169 const { video, videoInputPath, resolution, copyCodecs, isPortraitMode } = options
170
9c6ca37f
C
171 const baseHlsDirectory = join(HLS_STREAMING_PLAYLIST_DIRECTORY, video.uuid)
172 await ensureDir(join(HLS_STREAMING_PLAYLIST_DIRECTORY, video.uuid))
09209296 173
09209296 174 const outputPath = join(baseHlsDirectory, VideoStreamingPlaylistModel.getHlsPlaylistFilename(resolution))
d7a25329 175 const videoFilename = generateVideoStreamingPlaylistName(video.uuid, resolution)
09209296
C
176
177 const transcodeOptions = {
536598cf 178 type: 'hls' as 'hls',
9252a33d 179
09209296
C
180 inputPath: videoInputPath,
181 outputPath,
9252a33d
C
182
183 availableEncoders,
184 profile: 'default',
185
09209296 186 resolution,
d7a25329 187 copyCodecs,
09209296 188 isPortraitMode,
4c280004
C
189
190 hlsPlaylist: {
d7a25329 191 videoFilename
4c280004 192 }
09209296
C
193 }
194
d7a25329 195 await transcode(transcodeOptions)
09209296 196
6dd9de95 197 const playlistUrl = WEBSERVER.URL + VideoStreamingPlaylistModel.getHlsMasterPlaylistStaticPath(video.uuid)
09209296 198
d7a25329 199 const [ videoStreamingPlaylist ] = await VideoStreamingPlaylistModel.upsert({
09209296
C
200 videoId: video.id,
201 playlistUrl,
c6c0fa6c 202 segmentsSha256Url: WEBSERVER.URL + VideoStreamingPlaylistModel.getHlsSha256SegmentsStaticPath(video.uuid, video.isLive),
b5b68755 203 p2pMediaLoaderInfohashes: [],
594d0c6a 204 p2pMediaLoaderPeerVersion: P2P_MEDIA_LOADER_PEER_VERSION,
09209296
C
205
206 type: VideoStreamingPlaylistType.HLS
d7a25329
C
207 }, { returning: true }) as [ MStreamingPlaylistFilesVideo, boolean ]
208 videoStreamingPlaylist.Video = video
209
210 const newVideoFile = new VideoFileModel({
211 resolution,
212 extname: extnameUtil(videoFilename),
213 size: 0,
214 fps: -1,
215 videoStreamingPlaylistId: videoStreamingPlaylist.id
09209296 216 })
d7a25329
C
217
218 const videoFilePath = getVideoFilePath(videoStreamingPlaylist, newVideoFile)
219 const stats = await stat(videoFilePath)
220
221 newVideoFile.size = stats.size
222 newVideoFile.fps = await getVideoFileFPS(videoFilePath)
8319d6ae 223 newVideoFile.metadata = await getMetadataFromFile(videoFilePath)
d7a25329
C
224
225 await createTorrentAndSetInfoHash(videoStreamingPlaylist, newVideoFile)
226
c547bbf9 227 await VideoFileModel.customUpsert(newVideoFile, 'streaming-playlist', undefined)
e6122097 228 videoStreamingPlaylist.VideoFiles = await videoStreamingPlaylist.$get('VideoFiles')
d7a25329 229
b5b68755
C
230 videoStreamingPlaylist.p2pMediaLoaderInfohashes = VideoStreamingPlaylistModel.buildP2PMediaLoaderInfoHashes(
231 playlistUrl, videoStreamingPlaylist.VideoFiles
232 )
233 await videoStreamingPlaylist.save()
234
d7a25329
C
235 video.setHLSPlaylist(videoStreamingPlaylist)
236
237 await updateMasterHLSPlaylist(video)
c6c0fa6c 238 await updateSha256VODSegments(video)
d7a25329
C
239
240 return video
09209296
C
241}
242
536598cf
C
243// ---------------------------------------------------------------------------
244
098eb377 245export {
09209296 246 generateHlsPlaylist,
d7a25329
C
247 optimizeOriginalVideofile,
248 transcodeNewResolution,
536598cf
C
249 mergeAudioVideofile
250}
251
252// ---------------------------------------------------------------------------
253
453e83ea 254async function onVideoFileTranscoding (video: MVideoWithFile, videoFile: MVideoFile, transcodingPath: string, outputPath: string) {
536598cf
C
255 const stats = await stat(transcodingPath)
256 const fps = await getVideoFileFPS(transcodingPath)
8319d6ae 257 const metadata = await getMetadataFromFile(transcodingPath)
536598cf 258
fb0f7f82 259 await move(transcodingPath, outputPath, { overwrite: true })
536598cf 260
453e83ea
C
261 videoFile.size = stats.size
262 videoFile.fps = fps
8319d6ae 263 videoFile.metadata = metadata
536598cf 264
d7a25329 265 await createTorrentAndSetInfoHash(video, videoFile)
536598cf 266
fb0f7f82
C
267 await VideoFileModel.customUpsert(videoFile, 'video', undefined)
268 video.VideoFiles = await video.$get('VideoFiles')
536598cf
C
269
270 return video
098eb377 271}