]>
Commit | Line | Data |
---|---|---|
62549e6c | 1 | import execa from 'execa' |
88f16927 C |
2 | import { ensureDir, pathExists, writeFile } from 'fs-extra' |
3 | import { dirname, join } from 'path' | |
62549e6c C |
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 | ||
10 | const lTags = loggerTagsFactory('youtube-dl') | |
11 | ||
12 | const youtubeDLBinaryPath = join(CONFIG.STORAGE.BIN_DIR, CONFIG.IMPORT.VIDEOS.HTTP.YOUTUBE_DL_RELEASE.NAME) | |
13 | ||
14 | export class YoutubeDLCLI { | |
15 | ||
16 | static async safeGet () { | |
17 | if (!await pathExists(youtubeDLBinaryPath)) { | |
88f16927 C |
18 | await ensureDir(dirname(youtubeDLBinaryPath)) |
19 | ||
62549e6c C |
20 | await this.updateYoutubeDLBinary() |
21 | } | |
22 | ||
23 | return new YoutubeDLCLI() | |
24 | } | |
25 | ||
26 | static async updateYoutubeDLBinary () { | |
27 | const url = CONFIG.IMPORT.VIDEOS.HTTP.YOUTUBE_DL_RELEASE.URL | |
28 | ||
29 | logger.info('Updating youtubeDL binary from %s.', url, lTags()) | |
30 | ||
31 | const gotOptions = { context: { bodyKBLimit: 20_000 }, responseType: 'buffer' as 'buffer' } | |
32 | ||
33 | try { | |
34 | let gotResult = await peertubeGot(url, gotOptions) | |
35 | ||
36 | if (!isBinaryResponse(gotResult)) { | |
37 | const json = JSON.parse(gotResult.body.toString()) | |
38 | const latest = json.filter(release => release.prerelease === false)[0] | |
39 | if (!latest) throw new Error('Cannot find latest release') | |
40 | ||
41 | const releaseName = CONFIG.IMPORT.VIDEOS.HTTP.YOUTUBE_DL_RELEASE.NAME | |
42 | const releaseAsset = latest.assets.find(a => a.name === releaseName) | |
43 | if (!releaseAsset) throw new Error(`Cannot find appropriate release with name ${releaseName} in release assets`) | |
44 | ||
45 | gotResult = await peertubeGot(releaseAsset.browser_download_url, gotOptions) | |
46 | } | |
47 | ||
48 | if (!isBinaryResponse(gotResult)) { | |
49 | throw new Error('Not a binary response') | |
50 | } | |
51 | ||
52 | await writeFile(youtubeDLBinaryPath, gotResult.body) | |
53 | ||
54 | logger.info('youtube-dl updated %s.', youtubeDLBinaryPath, lTags()) | |
55 | } catch (err) { | |
56 | logger.error('Cannot update youtube-dl from %s.', url, { err, ...lTags() }) | |
57 | } | |
58 | } | |
59 | ||
5e2afe42 | 60 | static getYoutubeDLVideoFormat (enabledResolutions: VideoResolution[], useBestFormat: boolean) { |
62549e6c C |
61 | /** |
62 | * list of format selectors in order or preference | |
63 | * see https://github.com/ytdl-org/youtube-dl#format-selection | |
64 | * | |
65 | * case #1 asks for a mp4 using h264 (avc1) and the exact resolution in the hope | |
66 | * of being able to do a "quick-transcode" | |
67 | * case #2 is the first fallback. No "quick-transcode" means we can get anything else (like vp9) | |
68 | * case #3 is the resolution-degraded equivalent of #1, and already a pretty safe fallback | |
69 | * | |
70 | * in any case we avoid AV1, see https://github.com/Chocobozzz/PeerTube/issues/3499 | |
71 | **/ | |
5e2afe42 C |
72 | |
73 | let result: string[] = [] | |
74 | ||
75 | if (!useBestFormat) { | |
76 | const resolution = enabledResolutions.length === 0 | |
77 | ? VideoResolution.H_720P | |
78 | : Math.max(...enabledResolutions) | |
79 | ||
80 | result = [ | |
81 | `bestvideo[vcodec^=avc1][height=${resolution}]+bestaudio[ext=m4a]`, // case #1 | |
82 | `bestvideo[vcodec!*=av01][vcodec!*=vp9.2][height=${resolution}]+bestaudio`, // case #2 | |
83 | `bestvideo[vcodec^=avc1][height<=${resolution}]+bestaudio[ext=m4a]` // case # | |
84 | ] | |
85 | } | |
86 | ||
87 | return result.concat([ | |
88 | 'bestvideo[vcodec!*=av01][vcodec!*=vp9.2]+bestaudio', | |
62549e6c C |
89 | 'best[vcodec!*=av01][vcodec!*=vp9.2]', // case fallback for known formats |
90 | 'best' // Ultimate fallback | |
5e2afe42 | 91 | ]).join('/') |
62549e6c C |
92 | } |
93 | ||
94 | private constructor () { | |
95 | ||
96 | } | |
97 | ||
98 | download (options: { | |
99 | url: string | |
100 | format: string | |
101 | output: string | |
102 | processOptions: execa.NodeOptions | |
350b866f | 103 | timeout?: number |
62549e6c C |
104 | additionalYoutubeDLArgs?: string[] |
105 | }) { | |
106 | return this.run({ | |
107 | url: options.url, | |
108 | processOptions: options.processOptions, | |
7630e1c8 | 109 | timeout: options.timeout, |
62549e6c C |
110 | args: (options.additionalYoutubeDLArgs || []).concat([ '-f', options.format, '-o', options.output ]) |
111 | }) | |
112 | } | |
113 | ||
114 | async getInfo (options: { | |
115 | url: string | |
116 | format: string | |
117 | processOptions: execa.NodeOptions | |
118 | additionalYoutubeDLArgs?: string[] | |
119 | }) { | |
120 | const { url, format, additionalYoutubeDLArgs = [], processOptions } = options | |
121 | ||
122 | const completeArgs = additionalYoutubeDLArgs.concat([ '--dump-json', '-f', format ]) | |
123 | ||
124 | const data = await this.run({ url, args: completeArgs, processOptions }) | |
125 | const info = data.map(this.parseInfo) | |
126 | ||
127 | return info.length === 1 | |
128 | ? info[0] | |
129 | : info | |
130 | } | |
131 | ||
132 | async getSubs (options: { | |
133 | url: string | |
134 | format: 'vtt' | |
135 | processOptions: execa.NodeOptions | |
136 | }) { | |
137 | const { url, format, processOptions } = options | |
138 | ||
139 | const args = [ '--skip-download', '--all-subs', `--sub-format=${format}` ] | |
140 | ||
141 | const data = await this.run({ url, args, processOptions }) | |
142 | const files: string[] = [] | |
143 | ||
144 | const skipString = '[info] Writing video subtitles to: ' | |
145 | ||
146 | for (let i = 0, len = data.length; i < len; i++) { | |
147 | const line = data[i] | |
148 | ||
149 | if (line.indexOf(skipString) === 0) { | |
150 | files.push(line.slice(skipString.length)) | |
151 | } | |
152 | } | |
153 | ||
154 | return files | |
155 | } | |
156 | ||
157 | private async run (options: { | |
158 | url: string | |
159 | args: string[] | |
7630e1c8 | 160 | timeout?: number |
62549e6c C |
161 | processOptions: execa.NodeOptions |
162 | }) { | |
7630e1c8 | 163 | const { url, args, timeout, processOptions } = options |
62549e6c C |
164 | |
165 | let completeArgs = this.wrapWithProxyOptions(args) | |
166 | completeArgs = this.wrapWithIPOptions(completeArgs) | |
167 | completeArgs = this.wrapWithFFmpegOptions(completeArgs) | |
168 | ||
22c77786 | 169 | const { PYTHON_PATH } = CONFIG.IMPORT.VIDEOS.HTTP.YOUTUBE_DL_RELEASE |
7630e1c8 C |
170 | const subProcess = execa(PYTHON_PATH, [ youtubeDLBinaryPath, ...completeArgs, url ], processOptions) |
171 | ||
172 | if (timeout) { | |
173 | setTimeout(() => subProcess.cancel(), timeout) | |
174 | } | |
175 | ||
176 | const output = await subProcess | |
62549e6c | 177 | |
b2ad0090 | 178 | logger.debug('Runned youtube-dl command.', { command: output.command, ...lTags() }) |
62549e6c C |
179 | |
180 | return output.stdout | |
181 | ? output.stdout.trim().split(/\r?\n/) | |
182 | : undefined | |
183 | } | |
184 | ||
185 | private wrapWithProxyOptions (args: string[]) { | |
186 | if (isProxyEnabled()) { | |
187 | logger.debug('Using proxy %s for YoutubeDL', getProxy(), lTags()) | |
188 | ||
189 | return [ '--proxy', getProxy() ].concat(args) | |
190 | } | |
191 | ||
192 | return args | |
193 | } | |
194 | ||
195 | private wrapWithIPOptions (args: string[]) { | |
196 | if (CONFIG.IMPORT.VIDEOS.HTTP.FORCE_IPV4) { | |
197 | logger.debug('Force ipv4 for YoutubeDL') | |
198 | ||
199 | return [ '--force-ipv4' ].concat(args) | |
200 | } | |
201 | ||
202 | return args | |
203 | } | |
204 | ||
205 | private wrapWithFFmpegOptions (args: string[]) { | |
206 | if (process.env.FFMPEG_PATH) { | |
207 | logger.debug('Using ffmpeg location %s for YoutubeDL', process.env.FFMPEG_PATH, lTags()) | |
208 | ||
209 | return [ '--ffmpeg-location', process.env.FFMPEG_PATH ].concat(args) | |
210 | } | |
211 | ||
212 | return args | |
213 | } | |
214 | ||
215 | private parseInfo (data: string) { | |
216 | return JSON.parse(data) | |
217 | } | |
218 | } |