@adonis-agora/media
Version:
Media-library for AdonisJS — owner collections (MIME whitelist, single-file replace, ordering), image conversions (eager/lazy), pluggable content transformers (HLS video via mediabunny, metadata probe, image blur-up placeholder), and column attachments, a
186 lines • 7.88 kB
JavaScript
import { isRelativeUri, rewriteHlsPlaylist } from './hls/playlist.js';
/** Content type of an HLS playlist (RFC 8216). */
export const HLS_MIME_TYPE = 'application/vnd.apple.mpegurl';
/** Content type of a DASH manifest (ISO/IEC 23009-1). */
export const DASH_MIME_TYPE = 'application/dash+xml';
/** Content-Type of a WebVTT file (a storyboard's `storyboard.vtt`, a captions track). */
export const WEBVTT_MIME_TYPE = 'text/vtt';
/** Whether a package file is a WebVTT — served as text, its package references signed. */
export function isWebVtt(file) {
return file.split(/[?#]/, 1)[0].toLowerCase().endsWith('.vtt');
}
/**
* Rewrite the cue payload lines of a WebVTT through `rewrite` (`undefined` = keep the line).
* Header, `NOTE`/`STYLE`/`REGION` blocks, cue identifiers and timing lines are never passed to it —
* only the text that follows a timing line, up to the blank line ending the cue.
*/
export function rewriteWebVtt(content, rewrite) {
let inPayload = false;
return content
.split(/(?<=\n)/)
.map((raw) => {
const line = raw.replace(/\r?\n$/, '');
if (line.trim() === '') {
inPayload = false;
return raw;
}
if (line.includes('-->')) {
inPayload = true;
return raw;
}
if (!inPayload)
return raw;
const rewritten = rewrite(line.trim());
return rewritten === undefined ? raw : `${rewritten}${raw.slice(line.length)}`;
})
.join('');
}
/** Format of a manifest file, by extension; `undefined` for anything else. */
export function streamFormatOf(file) {
const clean = file.split(/[?#]/, 1)[0].toLowerCase();
if (clean.endsWith('.m3u8'))
return 'hls';
if (clean.endsWith('.mpd'))
return 'dash';
return undefined;
}
/**
* The streaming entry points of a record. A conversion counts when it carries a manifest: the
* ones `transformers.video()` records (`meta.hlsEntry`, `meta.dashManifest` — both for a CMAF
* package, HLS first), or an entry artifact that is one.
*
* Without `conversions`, every HLS entry comes before every DASH one (iOS plays only HLS). With
* `conversions`, they restrict the entries and set their order exactly, conversion by conversion.
*/
export function streamEntries(record, conversions) {
const names = conversions ?? Object.keys(record.conversions);
const entries = [];
for (const conversion of names) {
const variant = record.conversions[conversion];
if (!variant?.path || !variant.files)
continue;
const prefix = variant.prefix ?? variant.path.slice(0, variant.path.lastIndexOf('/') + 1);
const entry = variant.path.slice(prefix.length);
const manifests = [variant.meta?.hlsEntry, variant.meta?.dashManifest, entry].filter((file) => typeof file === 'string' && variant.files.includes(file));
const own = [];
for (const file of new Set(manifests)) {
const format = streamFormatOf(file);
if (format && !own.some((e) => e.format === format))
own.push({ conversion, format, file });
}
entries.push(...own.sort((a, b) => (a.format === b.format ? 0 : a.format === 'hls' ? -1 : 1)));
}
if (conversions)
return entries;
// Stable: HLS first, keeping the conversions' order within a format.
return [
...entries.filter((e) => e.format === 'hls'),
...entries.filter((e) => e.format === 'dash'),
];
}
/** Content type for one file of a streaming package, by extension. */
export function streamArtifactContentType(file) {
const lower = file.toLowerCase();
if (lower.endsWith('.m3u8'))
return HLS_MIME_TYPE;
if (lower.endsWith('.mpd'))
return DASH_MIME_TYPE;
if (lower.endsWith('.ts'))
return 'video/mp2t';
if (lower.endsWith('.m4s') || lower.endsWith('.mp4'))
return 'video/mp4';
if (lower.endsWith('.m4a'))
return 'audio/mp4';
if (lower.endsWith('.aac'))
return 'audio/aac';
if (lower.endsWith('.mp3'))
return 'audio/mpeg';
if (lower.endsWith('.vtt'))
return WEBVTT_MIME_TYPE;
// Storyboard sprite sheets (timeline thumbnails) live in the same package.
if (lower.endsWith('.jpg') || lower.endsWith('.jpeg'))
return 'image/jpeg';
return undefined;
}
/** Append a query string (`exp=…&sig=…`, no `?`) to a URI that may already carry one. */
export function withQuery(uri, query) {
if (query === '')
return uri;
const hash = uri.indexOf('#');
const base = hash === -1 ? uri : uri.slice(0, hash);
const fragment = hash === -1 ? '' : uri.slice(hash);
return `${base}${base.includes('?') ? '&' : '?'}${query}${fragment}`;
}
/** DASH attributes holding a URL or URL template. */
const DASH_URL_ATTRIBUTE = /\b(initialization|media|sourceURL)="([^"]*)"/g;
const DASH_BASE_URL = /<BaseURL([^>]*)>([^<]*)<\/BaseURL>/g;
/**
* Rewrite every **relative** URL of a DASH manifest through `rewrite`: `SegmentTemplate`
* `initialization`/`media` (templates such as `chunk-$Number%05d$.m4s` included — whatever is
* appended stays outside the `$…$` identifiers), `SegmentURL`/`Initialization` `sourceURL` and
* `media`, and `<BaseURL>` text. `rewrite` gets and returns raw URLs; XML escaping is
* handled here. Absolute references and everything else stay byte for byte.
*/
export async function rewriteDashManifest(content, rewrite) {
const apply = async (escaped) => {
const uri = unescapeXml(escaped);
if (uri === '' || !isRelativeUri(uri))
return escaped;
return escapeXml(await rewrite(uri));
};
let output = await replaceAsync(content, DASH_URL_ATTRIBUTE, async (match) => {
const [, name, value] = match;
return `${name}="${await apply(value)}"`;
});
output = await replaceAsync(output, DASH_BASE_URL, async (match) => {
const [, attributes, value] = match;
return `<BaseURL${attributes}>${await apply(value.trim())}</BaseURL>`;
});
return output;
}
/**
* Add `query` to every relative reference of a manifest (`.m3u8` or `.mpd`) — how a signature
* travels from the manifest request to the segment requests it leads to.
*
* A WebVTT (`.vtt`) is signed too, but only on the cue lines `isArtifact` recognizes as files of
* the package (a storyboard's `storyboard-001.jpg#xywh=…`, the query landing before the fragment):
* a captions track's spoken text is never touched.
*/
export async function signManifest(file, content, query, isArtifact = () => false) {
if (query === '')
return content;
const format = streamFormatOf(file);
if (format === 'hls')
return rewriteHlsPlaylist(content, (ref) => withQuery(ref.uri, query));
if (format === 'dash')
return rewriteDashManifest(content, (uri) => withQuery(uri, query));
if (isWebVtt(file)) {
return rewriteWebVtt(content, (line) => isRelativeUri(line) && isArtifact(line) ? withQuery(line, query) : undefined);
}
return content;
}
async function replaceAsync(input, pattern, replacer) {
let output = '';
let consumed = 0;
for (const match of input.matchAll(pattern)) {
output += input.slice(consumed, match.index) + (await replacer(match));
consumed = (match.index ?? 0) + match[0].length;
}
return output + input.slice(consumed);
}
function escapeXml(value) {
return value
.replace(/&/g, '&')
.replace(/"/g, '"')
.replace(/</g, '<')
.replace(/>/g, '>');
}
function unescapeXml(value) {
return value
.replace(/"/g, '"')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/'/g, "'")
.replace(/&/g, '&');
}
//# sourceMappingURL=streaming.js.map