Files
play-dl-test/play-dl/YouTube/classes/LiveStream.ts

472 lines
14 KiB
TypeScript
Raw Normal View History

2021-10-28 19:40:19 +02:00
import { Readable } from 'node:stream';
import { IncomingMessage } from 'node:http';
2021-09-29 20:23:16 +05:30
import { parseAudioFormats, StreamOptions, StreamType } from '../stream';
2021-10-11 18:38:08 +05:30
import { ProxyOptions as Proxy, request, request_stream } from '../../Request';
2021-09-03 17:55:21 +05:30
import { video_info } from '..';
2021-08-20 12:06:12 +05:30
2021-09-17 14:36:32 +05:30
export interface FormatInterface {
url: string;
targetDurationSec: number;
maxDvrDurationSec: number;
2021-08-20 12:06:12 +05:30
}
2021-11-18 13:06:55 +05:30
/**
* YouTube Live Stream class for playing audio from Live Stream videos.
*/
export class LiveStream {
/**
* Readable Stream through which data passes
*/
2021-10-11 17:29:10 +05:30
stream: Readable;
2021-11-18 13:06:55 +05:30
/**
* Type of audio data that we recieved from live stream youtube url.
*/
2021-09-17 14:36:32 +05:30
type: StreamType;
2021-11-18 13:06:55 +05:30
/**
* Base URL in dash manifest file.
*/
2021-09-17 14:36:32 +05:30
private base_url: string;
2021-11-18 13:06:55 +05:30
/**
* Given Dash URL.
*/
2021-09-17 14:36:32 +05:30
private url: string;
2021-11-18 13:06:55 +05:30
/**
* Interval to fetch data again to dash url.
*/
2021-09-17 14:36:32 +05:30
private interval: number;
2021-11-18 13:06:55 +05:30
/**
* Sequence count of urls in dash file.
*/
2021-09-17 14:36:32 +05:30
private packet_count: number;
2021-11-18 13:06:55 +05:30
/**
* Timer that creates loop from interval time provided.
*/
2021-10-05 18:47:09 +05:30
private timer: Timer;
2021-11-18 13:06:55 +05:30
/**
* Live Stream Video url.
*/
2021-09-17 14:36:32 +05:30
private video_url: string;
2021-11-18 13:06:55 +05:30
/**
* Timer used to update dash url so as to avoid 404 errors after long hours of streaming.
*
* It updates dash_url every 30 minutes.
*/
2021-10-05 18:47:09 +05:30
private dash_timer: Timer;
2021-11-18 13:06:55 +05:30
/**
* Segments of url that we recieve in dash file.
*
* base_url + segment_urls[0] = One complete url for one segment.
*/
2021-09-17 14:36:32 +05:30
private segments_urls: string[];
2021-11-18 13:06:55 +05:30
/**
* Incoming message that we recieve.
*
* Storing this is essential.
* This helps to destroy the TCP connection completely if you stopped player in between the stream
*/
2021-09-17 14:36:32 +05:30
private request: IncomingMessage | null;
2021-11-18 13:06:55 +05:30
/**
* Live Stream Class Constructor
* @param dash_url dash manifest URL
* @param target_interval interval time for fetching dash data again
* @param video_url Live Stream video url.
*/
2021-09-17 14:36:32 +05:30
constructor(dash_url: string, target_interval: number, video_url: string) {
2021-11-19 13:49:21 +05:30
this.stream = new Readable({ highWaterMark: 5 * 1000 * 1000, read() {} });
2021-09-17 14:36:32 +05:30
this.type = StreamType.Arbitrary;
this.url = dash_url;
this.base_url = '';
this.segments_urls = [];
this.packet_count = 0;
this.request = null;
this.video_url = video_url;
2021-10-05 18:47:09 +05:30
this.interval = target_interval || 0;
this.timer = new Timer(() => {
this.start();
}, this.interval);
this.dash_timer = new Timer(() => {
this.dash_timer.reuse();
2021-09-17 14:36:32 +05:30
this.dash_updater();
2021-10-05 18:47:09 +05:30
}, 1800);
2021-09-21 22:04:45 +05:30
this.stream.on('close', () => {
2021-09-17 14:36:32 +05:30
this.cleanup();
});
2021-09-17 14:36:32 +05:30
this.start();
2021-08-20 12:06:12 +05:30
}
2021-11-18 13:06:55 +05:30
/**
* Updates dash url.
*
* Used by dash_timer for updating dash_url every 30 minutes.
*/
2021-09-17 14:36:32 +05:30
private async dash_updater() {
const info = await video_info(this.video_url);
if (
info.LiveStreamData.isLive === true &&
info.LiveStreamData.hlsManifestUrl !== null &&
2021-09-28 19:20:58 +05:30
info.video_details.durationInSec === 0
2021-09-17 14:36:32 +05:30
) {
2021-11-18 15:38:25 +05:30
this.url = info.LiveStreamData.dashManifestUrl as string;
2021-09-03 17:55:21 +05:30
}
}
2021-11-18 13:06:55 +05:30
/**
* Parses data recieved from dash_url.
*
* Updates base_url , segments_urls array.
*/
2021-09-17 14:36:32 +05:30
private async dash_getter() {
const response = await request(this.url);
const audioFormat = response
.split('<AdaptationSet id="0"')[1]
.split('</AdaptationSet>')[0]
.split('</Representation>');
if (audioFormat[audioFormat.length - 1] === '') audioFormat.pop();
this.base_url = audioFormat[audioFormat.length - 1].split('<BaseURL>')[1].split('</BaseURL>')[0];
const list = audioFormat[audioFormat.length - 1].split('<SegmentList>')[1].split('</SegmentList>')[0];
this.segments_urls = list.replace(new RegExp('<SegmentURL media="', 'g'), '').split('"/>');
if (this.segments_urls[this.segments_urls.length - 1] === '') this.segments_urls.pop();
2021-08-20 12:06:12 +05:30
}
2021-11-18 13:06:55 +05:30
/**
* This cleans every used variable in class.
*
* This is used to prevent re-use of this class and helping garbage collector to collect it.
*/
2021-09-17 14:36:32 +05:30
private cleanup() {
2021-10-05 18:47:09 +05:30
this.timer.destroy();
this.dash_timer.destroy();
2021-09-17 14:36:32 +05:30
this.request?.destroy();
this.video_url = '';
this.request = null;
this.url = '';
this.base_url = '';
this.segments_urls = [];
this.packet_count = 0;
this.interval = 0;
2021-08-20 12:06:12 +05:30
}
2021-11-18 13:06:55 +05:30
/**
* This starts function in Live Stream Class.
*
* Gets data from dash url and pass it to dash getter function.
* Get data from complete segment url and pass data to Stream.
*/
2021-09-17 14:36:32 +05:30
private async start() {
2021-09-21 22:04:45 +05:30
if (this.stream.destroyed) {
2021-09-17 14:36:32 +05:30
this.cleanup();
return;
2021-08-21 18:55:45 +05:30
}
2021-09-17 14:36:32 +05:30
await this.dash_getter();
if (this.segments_urls.length > 3) this.segments_urls.splice(0, this.segments_urls.length - 3);
if (this.packet_count === 0) this.packet_count = Number(this.segments_urls[0].split('sq/')[1].split('/')[0]);
for await (const segment of this.segments_urls) {
if (Number(segment.split('sq/')[1].split('/')[0]) !== this.packet_count) {
continue;
2021-08-27 15:08:23 +05:30
}
2021-09-17 14:36:32 +05:30
await new Promise(async (resolve, reject) => {
const stream = await request_stream(this.base_url + segment).catch((err: Error) => err);
if (stream instanceof Error) {
2021-09-21 22:04:45 +05:30
this.stream.emit('error', stream);
2021-09-17 14:36:32 +05:30
return;
2021-09-15 17:30:57 +05:30
}
2021-09-17 14:36:32 +05:30
this.request = stream;
2021-10-11 17:29:10 +05:30
stream.on('data', (c) => {
2021-10-12 14:09:14 +05:30
this.stream.push(c);
});
stream.on('end', () => {
2021-09-17 14:36:32 +05:30
this.packet_count++;
resolve('');
});
stream.once('error', (err) => {
2021-09-21 22:04:45 +05:30
this.stream.emit('error', err);
2021-09-17 14:36:32 +05:30
});
});
2021-08-20 12:06:12 +05:30
}
2021-10-09 16:18:05 +05:30
2021-10-05 18:47:09 +05:30
this.timer.reuse();
2021-08-20 12:06:12 +05:30
}
2021-11-18 13:06:55 +05:30
/**
* Deprecated Functions
*/
2021-10-05 18:47:09 +05:30
pause() {}
2021-11-18 13:06:55 +05:30
/**
* Deprecated Functions
*/
2021-10-05 18:47:09 +05:30
resume() {}
2021-08-20 12:06:12 +05:30
}
2021-09-29 20:23:16 +05:30
/**
2021-11-18 13:06:55 +05:30
* YouTube Stream Class for playing audio from normal videos.
2021-09-29 20:23:16 +05:30
*/
2021-09-21 22:04:45 +05:30
export class Stream {
2021-11-18 13:06:55 +05:30
/**
* Readable Stream through which data passes
*/
stream: Readable;
/**
* Type of audio data that we recieved from normal youtube url.
*/
type: StreamType;
/**
* Audio Endpoint Format Url to get data from.
*/
2021-09-17 14:36:32 +05:30
private url: string;
2021-11-18 13:06:55 +05:30
/**
* Used to calculate no of bytes data that we have recieved
*/
2021-09-17 14:36:32 +05:30
private bytes_count: number;
2021-11-18 13:06:55 +05:30
/**
* Calculate per second bytes by using contentLength (Total bytes) / Duration (in seconds)
*/
2021-09-17 14:36:32 +05:30
private per_sec_bytes: number;
2021-11-18 13:06:55 +05:30
/**
* Total length of audio file in bytes
*/
2021-09-17 14:36:32 +05:30
private content_length: number;
2021-11-18 13:06:55 +05:30
/**
* YouTube video url. [ Used only for retrying purposes only. ]
*/
2021-09-17 14:36:32 +05:30
private video_url: string;
2021-11-18 13:06:55 +05:30
/**
* Timer for looping data every 265 seconds.
*/
2021-10-05 18:47:09 +05:30
private timer: Timer;
2021-11-18 13:06:55 +05:30
/**
* Quality given by user. [ Used only for retrying purposes only. ]
*/
private quality: number;
2021-11-18 13:06:55 +05:30
/**
* Proxy config given by user. [ Used only for retrying purposes only. ]
*/
2021-10-02 13:26:50 +05:30
private proxy: Proxy[] | undefined;
2021-11-18 13:06:55 +05:30
/**
* Incoming message that we recieve.
*
* Storing this is essential.
* This helps to destroy the TCP connection completely if you stopped player in between the stream
*/
2021-09-17 14:36:32 +05:30
private request: IncomingMessage | null;
2021-11-18 13:06:55 +05:30
/**
* YouTube Stream Class constructor
* @param url Audio Endpoint url.
* @param type Type of Stream
* @param duration Duration of audio playback [ in seconds ]
* @param contentLength Total length of Audio file in bytes.
* @param video_url YouTube video url.
* @param options Options provided to stream function.
*/
2021-09-17 14:36:32 +05:30
constructor(
url: string,
type: StreamType,
duration: number,
contentLength: number,
video_url: string,
2021-09-29 20:23:16 +05:30
options: StreamOptions
2021-09-17 14:36:32 +05:30
) {
2021-11-19 13:49:21 +05:30
this.stream = new Readable({ highWaterMark: 5 * 1000 * 1000, read() {} });
2021-09-17 14:36:32 +05:30
this.url = url;
2021-09-29 20:23:16 +05:30
this.quality = options.quality as number;
2021-10-01 12:08:46 +05:30
this.proxy = options.proxy || undefined;
2021-09-17 14:36:32 +05:30
this.type = type;
this.bytes_count = 0;
this.video_url = video_url;
this.per_sec_bytes = Math.ceil(contentLength / duration);
this.content_length = contentLength;
this.request = null;
2021-10-05 18:47:09 +05:30
this.timer = new Timer(() => {
this.timer.reuse();
this.loop();
2021-10-08 17:49:53 +05:30
}, 265);
2021-09-21 22:04:45 +05:30
this.stream.on('close', () => {
2021-10-09 16:18:05 +05:30
this.timer.destroy();
2021-09-17 14:36:32 +05:30
this.cleanup();
});
this.loop();
2021-08-24 12:50:06 +05:30
}
2021-11-18 13:06:55 +05:30
/**
* Retry if we get 404 or 403 Errors.
*/
2021-09-17 14:36:32 +05:30
private async retry() {
2021-10-08 14:58:06 +05:30
const info = await video_info(this.video_url, { proxy: this.proxy });
const audioFormat = parseAudioFormats(info.format);
this.url = audioFormat[this.quality].url;
2021-09-13 10:23:18 +05:30
}
2021-11-18 13:06:55 +05:30
/**
* This cleans every used variable in class.
*
* This is used to prevent re-use of this class and helping garbage collector to collect it.
*/
2021-09-17 14:36:32 +05:30
private cleanup() {
this.request?.destroy();
this.request = null;
this.url = '';
2021-08-24 12:50:06 +05:30
}
2021-11-18 13:06:55 +05:30
/**
* Getting data from audio endpoint url and passing it to stream.
*
* If 404 or 403 occurs, it will retry again.
*/
2021-09-17 14:36:32 +05:30
private async loop() {
2021-09-21 22:04:45 +05:30
if (this.stream.destroyed) {
2021-10-09 16:18:05 +05:30
this.timer.destroy();
2021-09-17 14:36:32 +05:30
this.cleanup();
return;
2021-08-24 12:50:06 +05:30
}
2021-09-17 14:36:32 +05:30
const end: number = this.bytes_count + this.per_sec_bytes * 300;
const stream = await request_stream(this.url, {
headers: {
range: `bytes=${this.bytes_count}-${end >= this.content_length ? '' : end}`
2021-08-24 12:50:06 +05:30
}
2021-09-17 14:36:32 +05:30
}).catch((err: Error) => err);
if (stream instanceof Error) {
2021-09-21 22:04:45 +05:30
this.stream.emit('error', stream);
2021-09-17 14:36:32 +05:30
this.bytes_count = 0;
this.per_sec_bytes = 0;
this.cleanup();
return;
2021-09-15 12:24:56 +05:30
}
2021-09-17 14:36:32 +05:30
if (Number(stream.statusCode) >= 400) {
this.cleanup();
await this.retry();
2021-10-09 16:18:05 +05:30
this.timer.reuse();
2021-09-17 14:36:32 +05:30
this.loop();
return;
2021-09-13 10:23:18 +05:30
}
2021-09-17 14:36:32 +05:30
this.request = stream;
2021-10-11 17:29:10 +05:30
stream.on('data', (c) => {
2021-10-12 14:09:14 +05:30
this.stream.push(c);
});
2021-08-31 17:28:37 +05:30
stream.once('error', async () => {
this.cleanup();
2021-09-28 20:56:10 +05:30
await this.retry();
2021-10-09 16:18:05 +05:30
this.timer.reuse();
2021-09-28 20:56:10 +05:30
this.loop();
2021-09-17 14:36:32 +05:30
});
2021-08-31 17:28:37 +05:30
2021-09-03 17:55:21 +05:30
stream.on('data', (chunk: any) => {
2021-09-17 14:36:32 +05:30
this.bytes_count += chunk.length;
});
2021-08-24 12:50:06 +05:30
2021-09-10 10:14:44 +05:30
stream.on('end', () => {
2021-10-05 18:47:09 +05:30
if (end >= this.content_length) {
this.timer.destroy();
2021-11-07 15:54:21 +05:30
this.stream.push(null);
2021-10-09 16:18:05 +05:30
this.cleanup();
2021-10-05 18:47:09 +05:30
}
2021-09-17 14:36:32 +05:30
});
}
2021-11-18 13:06:55 +05:30
/**
* Pauses timer.
* Stops running of loop.
*
* Useful if you don't want to get excess data to be stored in stream.
*/
2021-10-05 18:47:09 +05:30
pause() {
this.timer.pause();
}
2021-11-18 13:06:55 +05:30
/**
* Resumes timer.
* Starts running of loop.
*/
2021-10-05 18:47:09 +05:30
resume() {
this.timer.resume();
}
}
2021-11-18 13:06:55 +05:30
/**
* Timer Class.
*
* setTimeout + extra features ( re-starting, pausing, resuming ).
*/
2021-10-05 18:47:09 +05:30
export class Timer {
2021-11-18 13:06:55 +05:30
/**
* Boolean for checking if Timer is destroyed or not.
*/
2021-10-05 18:47:09 +05:30
private destroyed: boolean;
2021-11-18 13:06:55 +05:30
/**
* Boolean for checking if Timer is paused or not.
*/
2021-10-05 18:47:09 +05:30
private paused: boolean;
2021-11-18 13:06:55 +05:30
/**
* setTimeout function
*/
2021-10-05 18:47:09 +05:30
private timer: NodeJS.Timer;
2021-11-18 13:06:55 +05:30
/**
* Callback to be executed once timer finishes.
*/
2021-10-05 18:47:09 +05:30
private callback: () => void;
2021-11-18 13:06:55 +05:30
/**
* Seconds time when it is started.
*/
2021-10-05 18:47:09 +05:30
private time_start: number;
2021-11-18 13:06:55 +05:30
/**
* Total time left.
*/
2021-10-05 18:47:09 +05:30
private time_left: number;
2021-11-18 13:06:55 +05:30
/**
* Total time given by user [ Used only for re-using timer. ]
*/
2021-10-05 18:47:09 +05:30
private time_total: number;
2021-11-18 13:06:55 +05:30
/**
* Constructor for Timer Class
* @param callback Function to execute when timer is up.
* @param time Total time to wait before execution.
*/
2021-10-05 18:47:09 +05:30
constructor(callback: () => void, time: number) {
this.callback = callback;
this.time_total = time;
this.time_left = time;
this.paused = false;
this.destroyed = false;
this.time_start = process.hrtime()[0];
this.timer = setTimeout(this.callback, this.time_total * 1000);
}
2021-11-18 13:06:55 +05:30
/**
* Pauses Timer
* @returns Boolean to tell that if it is paused or not.
*/
2021-10-05 18:47:09 +05:30
pause() {
if (!this.paused && !this.destroyed) {
this.paused = true;
clearTimeout(this.timer);
this.time_left = this.time_left - (process.hrtime()[0] - this.time_start);
return true;
} else return false;
}
2021-11-18 13:06:55 +05:30
/**
* Resumes Timer
* @returns Boolean to tell that if it is resumed or not.
*/
2021-10-05 18:47:09 +05:30
resume() {
if (this.paused && !this.destroyed) {
this.paused = false;
this.time_start = process.hrtime()[0];
this.timer = setTimeout(this.callback, this.time_left * 1000);
return true;
} else return false;
}
2021-11-18 13:06:55 +05:30
/**
* Reusing of timer
* @returns Boolean to tell if it is re-used or not.
*/
2021-10-05 18:47:09 +05:30
reuse() {
if (!this.destroyed) {
clearTimeout(this.timer);
this.time_left = this.time_total;
this.paused = false;
this.time_start = process.hrtime()[0];
this.timer = setTimeout(this.callback, this.time_total * 1000);
return true;
} else return false;
}
2021-11-18 13:06:55 +05:30
/**
* Destroy timer.
*
* It can't be used again.
*/
2021-10-05 18:47:09 +05:30
destroy() {
clearTimeout(this.timer);
this.destroyed = true;
this.callback = () => {};
this.time_total = 0;
this.time_left = 0;
this.paused = false;
this.time_start = 0;
}
2021-08-21 15:03:43 +05:30
}