Add ability to disable webtorrent
[oweals/peertube.git] / server / lib / job-queue / handlers / video-transcoding.ts
1 import * as Bull from 'bull'
2 import { VideoResolution } from '../../../../shared'
3 import { logger } from '../../../helpers/logger'
4 import { VideoModel } from '../../../models/video/video'
5 import { JobQueue } from '../job-queue'
6 import { federateVideoIfNeeded } from '../../activitypub'
7 import { retryTransactionWrapper } from '../../../helpers/database-utils'
8 import { sequelizeTypescript } from '../../../initializers'
9 import * as Bluebird from 'bluebird'
10 import { computeResolutionsToTranscode } from '../../../helpers/ffmpeg-utils'
11 import { generateHlsPlaylist, mergeAudioVideofile, optimizeOriginalVideofile, transcodeNewResolution } from '../../video-transcoding'
12 import { Notifier } from '../../notifier'
13 import { CONFIG } from '../../../initializers/config'
14 import { MVideoFullLight, MVideoUUID, MVideoWithFile } from '@server/typings/models'
15
16 interface BaseTranscodingPayload {
17   videoUUID: string
18   isNewVideo?: boolean
19 }
20
21 interface HLSTranscodingPayload extends BaseTranscodingPayload {
22   type: 'hls'
23   isPortraitMode?: boolean
24   resolution: VideoResolution
25   copyCodecs: boolean
26 }
27
28 interface NewResolutionTranscodingPayload extends BaseTranscodingPayload {
29   type: 'new-resolution'
30   isPortraitMode?: boolean
31   resolution: VideoResolution
32 }
33
34 interface MergeAudioTranscodingPayload extends BaseTranscodingPayload {
35   type: 'merge-audio'
36   resolution: VideoResolution
37 }
38
39 interface OptimizeTranscodingPayload extends BaseTranscodingPayload {
40   type: 'optimize'
41 }
42
43 export type VideoTranscodingPayload = HLSTranscodingPayload | NewResolutionTranscodingPayload
44   | OptimizeTranscodingPayload | MergeAudioTranscodingPayload
45
46 async function processVideoTranscoding (job: Bull.Job) {
47   const payload = job.data as VideoTranscodingPayload
48   logger.info('Processing video file in job %d.', job.id)
49
50   const video = await VideoModel.loadAndPopulateAccountAndServerAndTags(payload.videoUUID)
51   // No video, maybe deleted?
52   if (!video) {
53     logger.info('Do not process job %d, video does not exist.', job.id)
54     return undefined
55   }
56
57   if (payload.type === 'hls') {
58     await generateHlsPlaylist(video, payload.resolution, payload.copyCodecs, payload.isPortraitMode || false)
59
60     await retryTransactionWrapper(onHlsPlaylistGenerationSuccess, video)
61   } else if (payload.type === 'new-resolution') {
62     await transcodeNewResolution(video, payload.resolution, payload.isPortraitMode || false)
63
64     await retryTransactionWrapper(publishNewResolutionIfNeeded, video, payload)
65   } else if (payload.type === 'merge-audio') {
66     await mergeAudioVideofile(video, payload.resolution)
67
68     await retryTransactionWrapper(publishNewResolutionIfNeeded, video, payload)
69   } else {
70     await optimizeOriginalVideofile(video)
71
72     await retryTransactionWrapper(onVideoFileOptimizerSuccess, video, payload)
73   }
74
75   return video
76 }
77
78 async function onHlsPlaylistGenerationSuccess (video: MVideoFullLight) {
79   if (video === undefined) return undefined
80
81   // We generated the HLS playlist, we don't need the webtorrent files anymore if the admin disabled it
82   if (CONFIG.TRANSCODING.WEBTORRENT.ENABLED === false) {
83     for (const file of video.VideoFiles) {
84       await video.removeFile(file)
85       await file.destroy()
86     }
87
88     video.VideoFiles = []
89   }
90
91   return publishAndFederateIfNeeded(video)
92 }
93
94 async function publishNewResolutionIfNeeded (video: MVideoUUID, payload?: NewResolutionTranscodingPayload | MergeAudioTranscodingPayload) {
95   await publishAndFederateIfNeeded(video)
96
97   await createHlsJobIfEnabled(payload)
98 }
99
100 async function onVideoFileOptimizerSuccess (videoArg: MVideoWithFile, payload: OptimizeTranscodingPayload) {
101   if (videoArg === undefined) return undefined
102
103   // Outside the transaction (IO on disk)
104   const { videoFileResolution } = await videoArg.getMaxQualityResolution()
105
106   const { videoDatabase, videoPublished } = await sequelizeTypescript.transaction(async t => {
107     // Maybe the video changed in database, refresh it
108     let videoDatabase = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoArg.uuid, t)
109     // Video does not exist anymore
110     if (!videoDatabase) return undefined
111
112     // Create transcoding jobs if there are enabled resolutions
113     const resolutionsEnabled = computeResolutionsToTranscode(videoFileResolution)
114     logger.info(
115       'Resolutions computed for video %s and origin file height of %d.', videoDatabase.uuid, videoFileResolution,
116       { resolutions: resolutionsEnabled }
117     )
118
119     let videoPublished = false
120
121     const hlsPayload = Object.assign({}, payload, { resolution: videoDatabase.getMaxQualityFile().resolution })
122     await createHlsJobIfEnabled(hlsPayload)
123
124     if (resolutionsEnabled.length !== 0) {
125       const tasks: (Bluebird<Bull.Job<any>> | Promise<Bull.Job<any>>)[] = []
126
127       for (const resolution of resolutionsEnabled) {
128         let dataInput: VideoTranscodingPayload
129
130         if (CONFIG.TRANSCODING.WEBTORRENT.ENABLED) {
131           dataInput = {
132             type: 'new-resolution' as 'new-resolution',
133             videoUUID: videoDatabase.uuid,
134             resolution
135           }
136         } else if (CONFIG.TRANSCODING.HLS.ENABLED) {
137           dataInput = {
138             type: 'hls',
139             videoUUID: videoDatabase.uuid,
140             resolution,
141             isPortraitMode: false,
142             copyCodecs: false
143           }
144         }
145
146         const p = JobQueue.Instance.createJob({ type: 'video-transcoding', payload: dataInput })
147         tasks.push(p)
148       }
149
150       await Promise.all(tasks)
151
152       logger.info('Transcoding jobs created for uuid %s.', videoDatabase.uuid, { resolutionsEnabled })
153     } else {
154       // No transcoding to do, it's now published
155       videoPublished = await videoDatabase.publishIfNeededAndSave(t)
156
157       logger.info('No transcoding jobs created for video %s (no resolutions).', videoDatabase.uuid, { privacy: videoDatabase.privacy })
158     }
159
160     await federateVideoIfNeeded(videoDatabase, payload.isNewVideo, t)
161
162     return { videoDatabase, videoPublished }
163   })
164
165   if (payload.isNewVideo) Notifier.Instance.notifyOnNewVideoIfNeeded(videoDatabase)
166   if (videoPublished) Notifier.Instance.notifyOnVideoPublishedAfterTranscoding(videoDatabase)
167 }
168
169 // ---------------------------------------------------------------------------
170
171 export {
172   processVideoTranscoding,
173   publishNewResolutionIfNeeded
174 }
175
176 // ---------------------------------------------------------------------------
177
178 function createHlsJobIfEnabled (payload?: { videoUUID: string, resolution: number, isPortraitMode?: boolean }) {
179   // Generate HLS playlist?
180   if (payload && CONFIG.TRANSCODING.HLS.ENABLED) {
181     const hlsTranscodingPayload = {
182       type: 'hls' as 'hls',
183       videoUUID: payload.videoUUID,
184       resolution: payload.resolution,
185       isPortraitMode: payload.isPortraitMode,
186       copyCodecs: true
187     }
188
189     return JobQueue.Instance.createJob({ type: 'video-transcoding', payload: hlsTranscodingPayload })
190   }
191 }
192
193 async function publishAndFederateIfNeeded (video: MVideoUUID) {
194   const { videoDatabase, videoPublished } = await sequelizeTypescript.transaction(async t => {
195     // Maybe the video changed in database, refresh it
196     const videoDatabase = await VideoModel.loadAndPopulateAccountAndServerAndTags(video.uuid, t)
197     // Video does not exist anymore
198     if (!videoDatabase) return undefined
199
200     // We transcoded the video file in another format, now we can publish it
201     const videoPublished = await videoDatabase.publishIfNeededAndSave(t)
202
203     // If the video was not published, we consider it is a new one for other instances
204     await federateVideoIfNeeded(videoDatabase, videoPublished, t)
205
206     return { videoDatabase, videoPublished }
207   })
208
209   if (videoPublished) {
210     Notifier.Instance.notifyOnNewVideoIfNeeded(videoDatabase)
211     Notifier.Instance.notifyOnVideoPublishedAfterTranscoding(videoDatabase)
212   }
213 }