1 import execa from 'execa'
2 import { pathExists, writeFile } from 'fs-extra'
3 import { 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'
10 const lTags = loggerTagsFactory('youtube-dl')
12 const youtubeDLBinaryPath = join(CONFIG.STORAGE.BIN_DIR, CONFIG.IMPORT.VIDEOS.HTTP.YOUTUBE_DL_RELEASE.NAME)
14 export class YoutubeDLCLI {
16 static async safeGet () {
17 if (!await pathExists(youtubeDLBinaryPath)) {
18 await this.updateYoutubeDLBinary()
21 return new YoutubeDLCLI()
24 static async updateYoutubeDLBinary () {
25 const url = CONFIG.IMPORT.VIDEOS.HTTP.YOUTUBE_DL_RELEASE.URL
27 logger.info('Updating youtubeDL binary from %s.', url, lTags())
29 const gotOptions = { context: { bodyKBLimit: 20_000 }, responseType: 'buffer' as 'buffer' }
32 let gotResult = await peertubeGot(url, gotOptions)
34 if (!isBinaryResponse(gotResult)) {
35 const json = JSON.parse(gotResult.body.toString())
36 const latest = json.filter(release => release.prerelease === false)[0]
37 if (!latest) throw new Error('Cannot find latest release')
39 const releaseName = CONFIG.IMPORT.VIDEOS.HTTP.YOUTUBE_DL_RELEASE.NAME
40 const releaseAsset = latest.assets.find(a => a.name === releaseName)
41 if (!releaseAsset) throw new Error(`Cannot find appropriate release with name ${releaseName} in release assets`)
43 gotResult = await peertubeGot(releaseAsset.browser_download_url, gotOptions)
46 if (!isBinaryResponse(gotResult)) {
47 throw new Error('Not a binary response')
50 await writeFile(youtubeDLBinaryPath, gotResult.body)
52 logger.info('youtube-dl updated %s.', youtubeDLBinaryPath, lTags())
54 logger.error('Cannot update youtube-dl from %s.', url, { err, ...lTags() })
58 static getYoutubeDLVideoFormat (enabledResolutions: VideoResolution[]) {
60 * list of format selectors in order or preference
61 * see https://github.com/ytdl-org/youtube-dl#format-selection
63 * case #1 asks for a mp4 using h264 (avc1) and the exact resolution in the hope
64 * of being able to do a "quick-transcode"
65 * case #2 is the first fallback. No "quick-transcode" means we can get anything else (like vp9)
66 * case #3 is the resolution-degraded equivalent of #1, and already a pretty safe fallback
68 * in any case we avoid AV1, see https://github.com/Chocobozzz/PeerTube/issues/3499
70 const resolution = enabledResolutions.length === 0
71 ? VideoResolution.H_720P
72 : Math.max(...enabledResolutions)
75 `bestvideo[vcodec^=avc1][height=${resolution}]+bestaudio[ext=m4a]`, // case #1
76 `bestvideo[vcodec!*=av01][vcodec!*=vp9.2][height=${resolution}]+bestaudio`, // case #2
77 `bestvideo[vcodec^=avc1][height<=${resolution}]+bestaudio[ext=m4a]`, // case #3
78 `bestvideo[vcodec!*=av01][vcodec!*=vp9.2]+bestaudio`,
79 'best[vcodec!*=av01][vcodec!*=vp9.2]', // case fallback for known formats
80 'best' // Ultimate fallback
84 private constructor () {
92 processOptions: execa.NodeOptions
93 additionalYoutubeDLArgs?: string[]
97 processOptions: options.processOptions,
98 args: (options.additionalYoutubeDLArgs || []).concat([ '-f', options.format, '-o', options.output ])
102 async getInfo (options: {
105 processOptions: execa.NodeOptions
106 additionalYoutubeDLArgs?: string[]
108 const { url, format, additionalYoutubeDLArgs = [], processOptions } = options
110 const completeArgs = additionalYoutubeDLArgs.concat([ '--dump-json', '-f', format ])
112 const data = await this.run({ url, args: completeArgs, processOptions })
113 const info = data.map(this.parseInfo)
115 return info.length === 1
120 async getSubs (options: {
123 processOptions: execa.NodeOptions
125 const { url, format, processOptions } = options
127 const args = [ '--skip-download', '--all-subs', `--sub-format=${format}` ]
129 const data = await this.run({ url, args, processOptions })
130 const files: string[] = []
132 const skipString = '[info] Writing video subtitles to: '
134 for (let i = 0, len = data.length; i < len; i++) {
137 if (line.indexOf(skipString) === 0) {
138 files.push(line.slice(skipString.length))
145 private async run (options: {
148 processOptions: execa.NodeOptions
150 const { url, args, processOptions } = options
152 let completeArgs = this.wrapWithProxyOptions(args)
153 completeArgs = this.wrapWithIPOptions(completeArgs)
154 completeArgs = this.wrapWithFFmpegOptions(completeArgs)
156 const { PYTHON_PATH } = CONFIG.IMPORT.VIDEOS.HTTP.YOUTUBE_DL_RELEASE
157 const output = await execa(PYTHON_PATH, [ youtubeDLBinaryPath, ...completeArgs, url ], processOptions)
159 logger.debug('Runned youtube-dl command.', { command: output.command, ...lTags() })
162 ? output.stdout.trim().split(/\r?\n/)
166 private wrapWithProxyOptions (args: string[]) {
167 if (isProxyEnabled()) {
168 logger.debug('Using proxy %s for YoutubeDL', getProxy(), lTags())
170 return [ '--proxy', getProxy() ].concat(args)
176 private wrapWithIPOptions (args: string[]) {
177 if (CONFIG.IMPORT.VIDEOS.HTTP.FORCE_IPV4) {
178 logger.debug('Force ipv4 for YoutubeDL')
180 return [ '--force-ipv4' ].concat(args)
186 private wrapWithFFmpegOptions (args: string[]) {
187 if (process.env.FFMPEG_PATH) {
188 logger.debug('Using ffmpeg location %s for YoutubeDL', process.env.FFMPEG_PATH, lTags())
190 return [ '--ffmpeg-location', process.env.FFMPEG_PATH ].concat(args)
196 private parseInfo (data: string) {
197 return JSON.parse(data)