夸克增加多线程播放
This commit is contained in:
@@ -153,6 +153,7 @@ export interface AdminConfig {
|
||||
Cookie: string;
|
||||
SavePath: string;
|
||||
PlayMode?: 'direct_first' | 'transcode_first';
|
||||
MultiThreadPlayback?: boolean;
|
||||
};
|
||||
Mobile?: {
|
||||
Enabled: boolean;
|
||||
|
||||
@@ -725,6 +725,7 @@ export function configSelfCheck(adminConfig: AdminConfig): AdminConfig {
|
||||
Cookie: '',
|
||||
SavePath: '/',
|
||||
PlayMode: 'transcode_first',
|
||||
MultiThreadPlayback: false,
|
||||
},
|
||||
Mobile: {
|
||||
Enabled: false,
|
||||
@@ -763,11 +764,15 @@ export function configSelfCheck(adminConfig: AdminConfig): AdminConfig {
|
||||
Cookie: '',
|
||||
SavePath: '/',
|
||||
PlayMode: 'transcode_first',
|
||||
MultiThreadPlayback: false,
|
||||
};
|
||||
}
|
||||
if (!adminConfig.NetDiskConfig.Quark.PlayMode) {
|
||||
adminConfig.NetDiskConfig.Quark.PlayMode = 'transcode_first';
|
||||
}
|
||||
if (adminConfig.NetDiskConfig.Quark.MultiThreadPlayback === undefined) {
|
||||
adminConfig.NetDiskConfig.Quark.MultiThreadPlayback = false;
|
||||
}
|
||||
|
||||
if (!adminConfig.NetDiskConfig.Mobile) {
|
||||
adminConfig.NetDiskConfig.Mobile = {
|
||||
|
||||
@@ -0,0 +1,179 @@
|
||||
import type { QuarkRangeWindow } from './quark.client';
|
||||
|
||||
const DEFAULT_CHUNK_SIZE = 1024 * 1024;
|
||||
const DEFAULT_CONCURRENCY = 8;
|
||||
const DEFAULT_CHUNK_RETRIES = 2;
|
||||
const RETRY_BASE_DELAY_MS = 300;
|
||||
|
||||
function buildRangeHeader(start: number, end: number) {
|
||||
return `bytes=${start}-${end}`;
|
||||
}
|
||||
|
||||
function splitRange(start: number, end: number, chunkSize = DEFAULT_CHUNK_SIZE) {
|
||||
const chunks: Array<{ index: number; start: number; end: number }> = [];
|
||||
let index = 0;
|
||||
for (let cursor = start; cursor <= end; cursor += chunkSize) {
|
||||
chunks.push({
|
||||
index,
|
||||
start: cursor,
|
||||
end: Math.min(cursor + chunkSize - 1, end),
|
||||
});
|
||||
index += 1;
|
||||
}
|
||||
return chunks;
|
||||
}
|
||||
|
||||
function isAbortError(error: unknown) {
|
||||
return (
|
||||
error instanceof Error &&
|
||||
(error.name === 'AbortError' || error.message.includes('aborted'))
|
||||
);
|
||||
}
|
||||
|
||||
function waitForRetry(ms: number, signal: AbortSignal) {
|
||||
if (signal.aborted) {
|
||||
throw new DOMException('Aborted', 'AbortError');
|
||||
}
|
||||
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
const timeoutId = setTimeout(() => {
|
||||
signal.removeEventListener('abort', onAbort);
|
||||
resolve();
|
||||
}, ms);
|
||||
|
||||
const onAbort = () => {
|
||||
clearTimeout(timeoutId);
|
||||
reject(new DOMException('Aborted', 'AbortError'));
|
||||
};
|
||||
|
||||
signal.addEventListener('abort', onAbort, { once: true });
|
||||
});
|
||||
}
|
||||
|
||||
async function fetchChunkOnce(
|
||||
url: string,
|
||||
headers: Record<string, string>,
|
||||
chunk: { start: number; end: number },
|
||||
signal: AbortSignal
|
||||
) {
|
||||
const response = await fetch(url, {
|
||||
headers: {
|
||||
...headers,
|
||||
Range: buildRangeHeader(chunk.start, chunk.end),
|
||||
},
|
||||
cache: 'no-store',
|
||||
signal,
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
try {
|
||||
await response.body?.cancel();
|
||||
} catch {
|
||||
void 0;
|
||||
}
|
||||
throw new Error(`chunk request failed (${response.status})`);
|
||||
}
|
||||
|
||||
return new Uint8Array(await response.arrayBuffer());
|
||||
}
|
||||
|
||||
async function fetchChunk(
|
||||
url: string,
|
||||
headers: Record<string, string>,
|
||||
chunk: { start: number; end: number },
|
||||
signal: AbortSignal,
|
||||
retries = DEFAULT_CHUNK_RETRIES
|
||||
) {
|
||||
let lastError: unknown;
|
||||
|
||||
for (let attempt = 0; attempt <= retries; attempt += 1) {
|
||||
try {
|
||||
return await fetchChunkOnce(url, headers, chunk, signal);
|
||||
} catch (error) {
|
||||
if (isAbortError(error) || attempt >= retries) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
lastError = error;
|
||||
await waitForRetry(RETRY_BASE_DELAY_MS * 2 ** attempt, signal);
|
||||
}
|
||||
}
|
||||
|
||||
throw lastError instanceof Error ? lastError : new Error('chunk request failed');
|
||||
}
|
||||
|
||||
export function createQuarkMultiThreadStream(input: {
|
||||
url: string;
|
||||
headers: Record<string, string>;
|
||||
window: QuarkRangeWindow;
|
||||
contentHeaders: Headers;
|
||||
status: number;
|
||||
}) {
|
||||
const { url, headers, window, contentHeaders, status } = input;
|
||||
const chunks = splitRange(window.start, window.end);
|
||||
const abortController = new AbortController();
|
||||
|
||||
const stream = new ReadableStream<Uint8Array>({
|
||||
async start(controller) {
|
||||
const results = new Map<number, Uint8Array>();
|
||||
let nextFetch = 0;
|
||||
let active = 0;
|
||||
let failed = false;
|
||||
|
||||
const done = new Promise<void>((resolve, reject) => {
|
||||
const launch = () => {
|
||||
if (failed) return;
|
||||
if (results.size >= chunks.length) {
|
||||
resolve();
|
||||
return;
|
||||
}
|
||||
|
||||
while (active < DEFAULT_CONCURRENCY && nextFetch < chunks.length) {
|
||||
const chunk = chunks[nextFetch];
|
||||
nextFetch += 1;
|
||||
active += 1;
|
||||
|
||||
fetchChunk(url, headers, chunk, abortController.signal)
|
||||
.then((data) => {
|
||||
results.set(chunk.index, data);
|
||||
if (results.size >= chunks.length) {
|
||||
resolve();
|
||||
}
|
||||
})
|
||||
.catch((error) => {
|
||||
if (isAbortError(error)) {
|
||||
return;
|
||||
}
|
||||
failed = true;
|
||||
reject(error);
|
||||
})
|
||||
.finally(() => {
|
||||
active -= 1;
|
||||
launch();
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
launch();
|
||||
});
|
||||
|
||||
await done;
|
||||
for (let index = 0; index < chunks.length; index += 1) {
|
||||
const data = results.get(index);
|
||||
if (!data) {
|
||||
throw new Error(`chunk missing (${index})`);
|
||||
}
|
||||
controller.enqueue(data);
|
||||
}
|
||||
controller.close();
|
||||
},
|
||||
cancel() {
|
||||
abortController.abort();
|
||||
},
|
||||
});
|
||||
|
||||
return new Response(stream, {
|
||||
status,
|
||||
headers: contentHeaders,
|
||||
});
|
||||
}
|
||||
@@ -8,6 +8,12 @@ export interface QuarkNetdiskSessionFile {
|
||||
pdirFid?: string;
|
||||
}
|
||||
|
||||
export interface QuarkPlayUrlCacheItem {
|
||||
name: string;
|
||||
url: string;
|
||||
priority: number;
|
||||
}
|
||||
|
||||
export interface QuarkNetdiskSession {
|
||||
id: string;
|
||||
provider: 'quark';
|
||||
@@ -18,6 +24,7 @@ export interface QuarkNetdiskSession {
|
||||
shareToken: string;
|
||||
files: QuarkNetdiskSessionFile[];
|
||||
savedFileIds: Record<string, string>;
|
||||
playUrlCaches: Record<string, { urls: QuarkPlayUrlCacheItem[]; expiresAt: number }>;
|
||||
playFolderFid?: string;
|
||||
playFolderPath?: string;
|
||||
createdAt: number;
|
||||
@@ -82,6 +89,7 @@ export function createQuarkNetdiskSession(input: {
|
||||
shareToken: input.shareToken,
|
||||
files: input.files,
|
||||
savedFileIds: {},
|
||||
playUrlCaches: {},
|
||||
createdAt: now,
|
||||
expiresAt: now + TTL_MS,
|
||||
};
|
||||
@@ -107,4 +115,3 @@ export function refreshQuarkNetdiskSession(id: string): QuarkNetdiskSession | nu
|
||||
sessionStore.set(id, session);
|
||||
return session;
|
||||
}
|
||||
|
||||
|
||||
@@ -41,5 +41,6 @@ export async function resolveQuarkSession(id: string) {
|
||||
cookie: quarkConfig.Cookie,
|
||||
savePath: quarkConfig.SavePath || '/',
|
||||
playMode,
|
||||
multiThreadPlayback: Boolean(quarkConfig.MultiThreadPlayback),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -43,6 +43,7 @@ export interface QuarkShareVideoListResult {
|
||||
}
|
||||
|
||||
export type QuarkPlayMode = 'direct_first' | 'transcode_first';
|
||||
export type QuarkRangeWindow = { start: number; end: number; total: number };
|
||||
|
||||
const VIDEO_EXTENSIONS = [
|
||||
'.mp4',
|
||||
@@ -809,3 +810,42 @@ export async function getQuarkPlayUrls(
|
||||
|
||||
return deduped;
|
||||
}
|
||||
|
||||
function parseContentRangeHeader(contentRange: string | null): QuarkRangeWindow | null {
|
||||
if (!contentRange) return null;
|
||||
const match = contentRange.match(/^bytes\s+(\d+)-(\d+)\/(\d+|\*)$/i);
|
||||
if (!match) return null;
|
||||
const start = Number(match[1]);
|
||||
const end = Number(match[2]);
|
||||
const total = Number(match[3]);
|
||||
if (!Number.isFinite(start) || !Number.isFinite(end) || !Number.isFinite(total)) return null;
|
||||
return { start, end, total };
|
||||
}
|
||||
|
||||
export async function probeQuarkPlayRange(
|
||||
url: string,
|
||||
headers: Record<string, string>,
|
||||
range?: string
|
||||
): Promise<{ response: Response; window: QuarkRangeWindow | null } | null> {
|
||||
const abortController = new AbortController();
|
||||
const timeoutId = setTimeout(() => abortController.abort(), 300000);
|
||||
try {
|
||||
const response = await fetch(url, {
|
||||
headers: {
|
||||
...headers,
|
||||
...(range ? { Range: range } : {}),
|
||||
},
|
||||
cache: 'no-store',
|
||||
signal: abortController.signal,
|
||||
});
|
||||
|
||||
if (!response.ok || !response.body) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const window = parseContentRangeHeader(response.headers.get('content-range'));
|
||||
return { response, window };
|
||||
} finally {
|
||||
clearTimeout(timeoutId);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user