/
index.js
214 lines (188 loc) · 6.23 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
const PassThrough = require('stream').PassThrough;
const getInfo = require('./info');
const utils = require('./utils');
const formatUtils = require('./format-utils');
const urlUtils = require('./url-utils');
const sig = require('./sig');
const miniget = require('miniget');
const m3u8stream = require('m3u8stream');
const { parseTimestamp } = require('m3u8stream');
/**
* @param {string} link
* @param {!Object} options
* @returns {ReadableStream}
*/
const ytdl = (link, options) => {
const stream = createStream(options);
ytdl.getInfo(link, options).then(info => {
downloadFromInfoCallback(stream, info, options);
}, stream.emit.bind(stream, 'error'));
return stream;
};
module.exports = ytdl;
ytdl.getBasicInfo = getInfo.getBasicInfo;
ytdl.getInfo = getInfo.getInfo;
ytdl.chooseFormat = formatUtils.chooseFormat;
ytdl.filterFormats = formatUtils.filterFormats;
ytdl.validateID = urlUtils.validateID;
ytdl.validateURL = urlUtils.validateURL;
ytdl.getURLVideoID = urlUtils.getURLVideoID;
ytdl.getVideoID = urlUtils.getVideoID;
ytdl.cache = {
sig: sig.cache,
info: getInfo.cache,
watch: getInfo.watchPageCache,
cookie: getInfo.cookieCache,
};
ytdl.version = require('../package.json').version;
const createStream = options => {
const stream = new PassThrough({
highWaterMark: (options && options.highWaterMark) || 1024 * 512,
});
stream._destroy = () => { stream.destroyed = true; };
return stream;
};
const pipeAndSetEvents = (req, stream, end) => {
// Forward events from the request to the stream.
[
'abort', 'request', 'response', 'error', 'redirect', 'retry', 'reconnect',
].forEach(event => {
req.prependListener(event, stream.emit.bind(stream, event));
});
req.pipe(stream, { end });
};
/**
* Chooses a format to download.
*
* @param {stream.Readable} stream
* @param {Object} info
* @param {Object} options
*/
const downloadFromInfoCallback = (stream, info, options) => {
options = options || {};
let err = utils.playError(info.player_response, ['UNPLAYABLE', 'LIVE_STREAM_OFFLINE', 'LOGIN_REQUIRED']);
if (err) {
stream.emit('error', err);
return;
}
if (!info.formats.length) {
stream.emit('error', Error('This video is unavailable'));
return;
}
let format;
try {
format = formatUtils.chooseFormat(info.formats, options);
} catch (e) {
stream.emit('error', e);
return;
}
stream.emit('info', info, format);
if (stream.destroyed) { return; }
let contentLength, downloaded = 0;
const ondata = chunk => {
downloaded += chunk.length;
stream.emit('progress', chunk.length, downloaded, contentLength);
};
if (options.IPv6Block) {
options.requestOptions = Object.assign({}, options.requestOptions, {
family: 6,
localAddress: utils.getRandomIPv6(options.IPv6Block),
});
}
// Download the file in chunks, in this case the default is 10MB,
// anything over this will cause youtube to throttle the download
const dlChunkSize = options.dlChunkSize || 1024 * 1024 * 10;
let req;
let shouldEnd = true;
if (format.isHLS || format.isDashMPD) {
req = m3u8stream(format.url, {
chunkReadahead: +info.live_chunk_readahead,
begin: options.begin || (format.isLive && Date.now()),
liveBuffer: options.liveBuffer,
requestOptions: options.requestOptions,
parser: format.isDashMPD ? 'dash-mpd' : 'm3u8',
id: format.itag,
});
req.on('progress', (segment, totalSegments) => {
stream.emit('progress', segment.size, segment.num, totalSegments);
});
pipeAndSetEvents(req, stream, shouldEnd);
} else {
const requestOptions = Object.assign({}, options.requestOptions, {
maxReconnects: 6,
maxRetries: 3,
backoff: { inc: 500, max: 10000 },
});
let shouldBeChunked = dlChunkSize !== 0 && (!format.hasAudio || !format.hasVideo);
if (shouldBeChunked) {
let start = (options.range && options.range.start) || 0;
let end = start + dlChunkSize;
const rangeEnd = options.range && options.range.end;
contentLength = options.range ?
(rangeEnd ? rangeEnd + 1 : parseInt(format.contentLength)) - start :
parseInt(format.contentLength);
const getNextChunk = () => {
if (!rangeEnd && end >= contentLength) end = 0;
if (rangeEnd && end > rangeEnd) end = rangeEnd;
shouldEnd = !end || end === rangeEnd;
requestOptions.headers = Object.assign({}, requestOptions.headers, {
Range: `bytes=${start}-${end || ''}`,
});
req = miniget(format.url, requestOptions);
req.on('data', ondata);
req.on('end', () => {
if (stream.destroyed) { return; }
if (end && end !== rangeEnd) {
start = end + 1;
end += dlChunkSize;
getNextChunk();
}
});
pipeAndSetEvents(req, stream, shouldEnd);
};
getNextChunk();
} else {
// Audio only and video only formats don't support begin
if (options.begin) {
format.url += `&begin=${parseTimestamp(options.begin)}`;
}
if (options.range && (options.range.start || options.range.end)) {
requestOptions.headers = Object.assign({}, requestOptions.headers, {
Range: `bytes=${options.range.start || '0'}-${options.range.end || ''}`,
});
}
req = miniget(format.url, requestOptions);
req.on('response', res => {
if (stream.destroyed) { return; }
contentLength = contentLength || parseInt(res.headers['content-length']);
});
req.on('data', ondata);
pipeAndSetEvents(req, stream, shouldEnd);
}
}
stream._destroy = () => {
stream.destroyed = true;
req.destroy();
req.end();
};
};
/**
* Can be used to download video after its `info` is gotten through
* `ytdl.getInfo()`. In case the user might want to look at the
* `info` object before deciding to download.
*
* @param {Object} info
* @param {!Object} options
* @returns {ReadableStream}
*/
ytdl.downloadFromInfo = (info, options) => {
const stream = createStream(options);
if (!info.full) {
throw Error('Cannot use `ytdl.downloadFromInfo()` when called ' +
'with info from `ytdl.getBasicInfo()`');
}
setImmediate(() => {
downloadFromInfoCallback(stream, info, options);
});
return stream;
};