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