1 import execa from 'execa'
2 import { ensureDir, pathExists, writeFile } from 'fs-extra'
3 import { dirname, join } from 'path'
4 import { CONFIG } from '@server/initializers/config'
5 import { VideoResolution } from '@shared/models'
6 import { logger, loggerTagsFactory } from '../logger'
7 import { getProxy, isProxyEnabled } from '../proxy'
8 import { isBinaryResponse, peertubeGot } from '../requests'
9 import { OptionsOfBufferResponseBody } from 'got/dist/source'
11 const lTags = loggerTagsFactory('youtube-dl')
13 const youtubeDLBinaryPath = join(CONFIG.STORAGE.BIN_DIR, CONFIG.IMPORT.VIDEOS.HTTP.YOUTUBE_DL_RELEASE.NAME)
15 export class YoutubeDLCLI {
17 static async safeGet () {
18 if (!await pathExists(youtubeDLBinaryPath)) {
19 await ensureDir(dirname(youtubeDLBinaryPath))
21 await this.updateYoutubeDLBinary()
24 return new YoutubeDLCLI()
27 static async updateYoutubeDLBinary () {
28 const url = CONFIG.IMPORT.VIDEOS.HTTP.YOUTUBE_DL_RELEASE.URL
30 logger.info('Updating youtubeDL binary from %s.', url, lTags())
32 const gotOptions: OptionsOfBufferResponseBody = {
33 context: { bodyKBLimit: 20_000 },
34 responseType: 'buffer' as 'buffer'
37 if (process.env.YOUTUBE_DL_DOWNLOAD_BEARER_TOKEN) {
38 gotOptions.headers = {
39 authorization: 'Bearer ' + process.env.YOUTUBE_DL_DOWNLOAD_BEARER_TOKEN
44 let gotResult = await peertubeGot(url, gotOptions)
46 if (!isBinaryResponse(gotResult)) {
47 const json = JSON.parse(gotResult.body.toString())
48 const latest = json.filter(release => release.prerelease === false)[0]
49 if (!latest) throw new Error('Cannot find latest release')
51 const releaseName = CONFIG.IMPORT.VIDEOS.HTTP.YOUTUBE_DL_RELEASE.NAME
52 const releaseAsset = latest.assets.find(a => a.name === releaseName)
53 if (!releaseAsset) throw new Error(`Cannot find appropriate release with name ${releaseName} in release assets`)
55 gotResult = await peertubeGot(releaseAsset.browser_download_url, gotOptions)
58 if (!isBinaryResponse(gotResult)) {
59 throw new Error('Not a binary response')
62 await writeFile(youtubeDLBinaryPath, gotResult.body)
64 logger.info('youtube-dl updated %s.', youtubeDLBinaryPath, lTags())
66 logger.error('Cannot update youtube-dl from %s.', url, { err, ...lTags() })
70 static getYoutubeDLVideoFormat (enabledResolutions: VideoResolution[], useBestFormat: boolean) {
72 * list of format selectors in order or preference
73 * see https://github.com/ytdl-org/youtube-dl#format-selection
75 * case #1 asks for a mp4 using h264 (avc1) and the exact resolution in the hope
76 * of being able to do a "quick-transcode"
77 * case #2 is the first fallback. No "quick-transcode" means we can get anything else (like vp9)
78 * case #3 is the resolution-degraded equivalent of #1, and already a pretty safe fallback
80 * in any case we avoid AV1, see https://github.com/Chocobozzz/PeerTube/issues/3499
83 let result: string[] = []
86 const resolution = enabledResolutions.length === 0
87 ? VideoResolution.H_720P
88 : Math.max(...enabledResolutions)
91 `bestvideo[vcodec^=avc1][height=${resolution}]+bestaudio[ext=m4a]`, // case #1
92 `bestvideo[vcodec!*=av01][vcodec!*=vp9.2][height=${resolution}]+bestaudio`, // case #2
93 `bestvideo[vcodec^=avc1][height<=${resolution}]+bestaudio[ext=m4a]` // case #
97 return result.concat([
98 'bestvideo[vcodec!*=av01][vcodec!*=vp9.2]+bestaudio',
99 'best[vcodec!*=av01][vcodec!*=vp9.2]', // case fallback for known formats
100 'bestvideo[ext=mp4]+bestaudio[ext=m4a]',
101 'best' // Ultimate fallback
105 private constructor () {
113 processOptions: execa.NodeOptions
115 additionalYoutubeDLArgs?: string[]
117 let args = options.additionalYoutubeDLArgs || []
118 args = args.concat([ '--merge-output-format', 'mp4', '-f', options.format, '-o', options.output ])
122 processOptions: options.processOptions,
123 timeout: options.timeout,
128 async getInfo (options: {
131 processOptions: execa.NodeOptions
132 additionalYoutubeDLArgs?: string[]
134 const { url, format, additionalYoutubeDLArgs = [], processOptions } = options
136 const completeArgs = additionalYoutubeDLArgs.concat([ '--dump-json', '-f', format ])
138 const data = await this.run({ url, args: completeArgs, processOptions })
139 if (!data) return undefined
141 const info = data.map(d => JSON.parse(d))
143 return info.length === 1
148 async getListInfo (options: {
150 latestVideosCount?: number
151 processOptions: execa.NodeOptions
152 }): Promise<{ upload_date: string, webpage_url: string }[]> {
153 const additionalYoutubeDLArgs = [ '--skip-download', '--playlist-reverse' ]
155 if (CONFIG.IMPORT.VIDEOS.HTTP.YOUTUBE_DL_RELEASE.NAME === 'yt-dlp') {
156 // Optimize listing videos only when using yt-dlp because it is bugged with youtube-dl when fetching a channel
157 additionalYoutubeDLArgs.push('--flat-playlist')
160 if (options.latestVideosCount !== undefined) {
161 additionalYoutubeDLArgs.push('--playlist-end', options.latestVideosCount.toString())
164 const result = await this.getInfo({
166 format: YoutubeDLCLI.getYoutubeDLVideoFormat([], false),
167 processOptions: options.processOptions,
168 additionalYoutubeDLArgs
171 if (!result) return result
172 if (!Array.isArray(result)) return [ result ]
177 async getSubs (options: {
180 processOptions: execa.NodeOptions
182 const { url, format, processOptions } = options
184 const args = [ '--skip-download', '--all-subs', `--sub-format=${format}` ]
186 const data = await this.run({ url, args, processOptions })
187 const files: string[] = []
189 const skipString = '[info] Writing video subtitles to: '
191 for (let i = 0, len = data.length; i < len; i++) {
194 if (line.indexOf(skipString) === 0) {
195 files.push(line.slice(skipString.length))
202 private async run (options: {
206 processOptions: execa.NodeOptions
208 const { url, args, timeout, processOptions } = options
210 let completeArgs = this.wrapWithProxyOptions(args)
211 completeArgs = this.wrapWithIPOptions(completeArgs)
212 completeArgs = this.wrapWithFFmpegOptions(completeArgs)
214 const { PYTHON_PATH } = CONFIG.IMPORT.VIDEOS.HTTP.YOUTUBE_DL_RELEASE
215 const subProcess = execa(PYTHON_PATH, [ youtubeDLBinaryPath, ...completeArgs, url ], processOptions)
218 setTimeout(() => subProcess.cancel(), timeout)
221 const output = await subProcess
223 logger.debug('Run youtube-dl command.', { command: output.command, ...lTags() })
226 ? output.stdout.trim().split(/\r?\n/)
230 private wrapWithProxyOptions (args: string[]) {
231 if (isProxyEnabled()) {
232 logger.debug('Using proxy %s for YoutubeDL', getProxy(), lTags())
234 return [ '--proxy', getProxy() ].concat(args)
240 private wrapWithIPOptions (args: string[]) {
241 if (CONFIG.IMPORT.VIDEOS.HTTP.FORCE_IPV4) {
242 logger.debug('Force ipv4 for YoutubeDL')
244 return [ '--force-ipv4' ].concat(args)
250 private wrapWithFFmpegOptions (args: string[]) {
251 if (process.env.FFMPEG_PATH) {
252 logger.debug('Using ffmpeg location %s for YoutubeDL', process.env.FFMPEG_PATH, lTags())
254 return [ '--ffmpeg-location', process.env.FFMPEG_PATH ].concat(args)