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