@stacksjs/video 0.75.674 → 0.75.685
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/browser.d.ts +10 -1
- package/dist/browser.js +1 -1
- package/dist/files.d.ts +1 -0
- package/dist/files.js +1 -1
- package/dist/index.d.ts +8 -1
- package/dist/index.js +1 -1
- package/package.json +4 -4
package/dist/browser.d.ts
CHANGED
|
@@ -33,15 +33,24 @@ export declare interface PrepareVideoUploadOptions {
|
|
|
33
33
|
maxOutputBytes?: number
|
|
34
34
|
signal?: AbortSignal
|
|
35
35
|
onProgress?: (ratio: number) => void
|
|
36
|
+
stallMs?: number
|
|
37
|
+
firstTickMs?: number
|
|
36
38
|
}
|
|
37
39
|
export declare interface PreparedVideoUpload {
|
|
38
40
|
video: Blob
|
|
39
41
|
poster?: Blob
|
|
40
42
|
converter: 'webcodecs' | null
|
|
41
|
-
reason?: 'unsupported' | 'already-ready' | 'too-large' | 'failed'
|
|
43
|
+
reason?: 'unsupported' | 'already-ready' | 'too-large' | 'failed' | 'stalled'
|
|
42
44
|
cause?: unknown
|
|
43
45
|
width?: number
|
|
44
46
|
height?: number
|
|
45
47
|
duration?: number
|
|
46
48
|
sourceBytes: number
|
|
47
49
|
}
|
|
50
|
+
/** A conversion that stopped moving, given up so the original can be sent. */
|
|
51
|
+
export declare class VideoPrepareStalledError extends Error {
|
|
52
|
+
/** @defaultValue 'VideoPrepareStalledError' */
|
|
53
|
+
name: string;
|
|
54
|
+
readonly stallMs: number;
|
|
55
|
+
constructor(stallMs: number);
|
|
56
|
+
}
|
package/dist/browser.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export function canPrepareVideoUpload(){const scope=globalThis;return["VideoDecoder","VideoEncoder","EncodedVideoChunk","VideoFrame","OffscreenCanvas"].every((name)=>typeof scope[name]==="function")}const isAbort=(error,signal)=>Boolean(signal?.aborted)||error?.name==="AbortError";export async function prepareVideoUpload(file,options={}){const original=(reason,cause)=>({video:file,converter:null,reason,sourceBytes:file.size,...cause===undefined?{}:{cause}});if(!canPrepareVideoUpload())return original("unsupported");
|
|
1
|
+
export function canPrepareVideoUpload(){const scope=globalThis;return["VideoDecoder","VideoEncoder","EncodedVideoChunk","VideoFrame","OffscreenCanvas"].every((name)=>typeof scope[name]==="function")}const isHidden=()=>Boolean(globalThis.document?.hidden);const isAbort=(error,signal)=>Boolean(signal?.aborted)||error?.name==="AbortError";const STALL_MS=20000;const FIRST_TICK_MS=60000;const FIRST_TICK_MS_PER_MB=250;export class VideoPrepareStalledError extends Error{stallMs;name="VideoPrepareStalledError";constructor(stallMs){super(`The clip did not move for ${Math.round(stallMs/1000)} seconds while it was converted`);this.stallMs=stallMs}}export async function prepareVideoUpload(file,options={}){const original=(reason,cause)=>({video:file,converter:null,reason,sourceBytes:file.size,...cause===undefined?{}:{cause}});if(!canPrepareVideoUpload())return original("unsupported");if(options.signal?.aborted)throw options.signal.reason??new DOMException("The upload was cancelled","AbortError");const work=new AbortController;const stallMs=options.stallMs??STALL_MS;const firstTickMs=options.firstTickMs??FIRST_TICK_MS+Math.round(file.size/1048576*FIRST_TICK_MS_PER_MB);let ticked=false;let settled=false;let watchdog;let stop=()=>{};const halted=new Promise((resolve)=>{stop=resolve});const watch=()=>{clearTimeout(watchdog);if(!stallMs||settled||isHidden())return;const budget=ticked?stallMs:Math.max(stallMs,firstTickMs);watchdog=setTimeout(()=>stop({stalled:new VideoPrepareStalledError(budget)}),budget)};const cancel=()=>stop({cancelled:options.signal.reason});options.signal?.addEventListener("abort",cancel,{once:true});const page=globalThis.document;page?.addEventListener?.("visibilitychange",watch);watch();const converting=(async()=>{const{prepareVideoForUpload}=await import("ts-videos/native-transcode");return prepareVideoForUpload(file,{maxLongEdge:options.maxLongEdge,maxShortEdge:options.maxShortEdge,maxFrameRate:options.maxFrameRate,videoBitrate:options.videoBitrate,poster:options.poster??true,maxOutputBytes:options.maxOutputBytes,signal:work.signal,onProgress:(progress)=>{if(settled)return;ticked=true;watch();options.onProgress?.(progress.ratio)}})})();try{const outcome=await Promise.race([converting.then((result)=>({result})),halted]);if("cancelled"in outcome){work.abort(outcome.cancelled);throw outcome.cancelled??new DOMException("The upload was cancelled","AbortError")}if("stalled"in outcome){work.abort(outcome.stalled);return original("stalled",outcome.stalled)}const{result}=outcome;if(result.unchanged)return{...original("already-ready"),width:result.width,height:result.height,duration:result.duration};return{video:result.video,poster:result.poster,converter:"webcodecs",width:result.width,height:result.height,duration:result.duration,sourceBytes:file.size}}catch(error){if(isAbort(error,options.signal))throw error;if(error?.name==="UploadVideoTooLargeError")return original("too-large",error);return original("failed",error)}finally{settled=true;clearTimeout(watchdog);options.signal?.removeEventListener("abort",cancel);page?.removeEventListener?.("visibilitychange",watch);converting.catch(()=>{})}}
|
package/dist/files.d.ts
CHANGED
package/dist/files.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{videoAssetHeaders}from"./index";export function parseByteRange(header,size){const match=/^bytes=(\d*)-(\d*)$/.exec(String(header??"").trim());if(!match||!match[1]&&!match[2])return null;if(!match[1]){const length=Math.min(Number(match[2]),size);return length>0?{start:size-length,end:size-1}:"unsatisfiable"}const start=Number(match[1]);if(start>=size)return"unsatisfiable";const end=match[2]?Math.min(Number(match[2]),size-1):size-1;return end>=start?{start,end}:"unsatisfiable"}const VIDEO_TYPES={mp4:"video/mp4",m4v:"video/mp4",mov:"video/quicktime",webm:"video/webm",m3u8:"application/vnd.apple.mpegurl",mpd:"application/dash+xml",m4s:"video/iso.segment",vtt:"text/vtt"};export function videoContentType(name){return VIDEO_TYPES[name.split(/[?#]/,1)[0].split(".").pop()?.toLowerCase()||""]||"application/octet-stream"}export function videoFileResponse(file,name,options={}){const size=file.size;const type=options.contentType||videoContentType(name);const range=parseByteRange(options.range,size);if(range==="unsatisfiable")return new Response(null,{status:416,headers:{"Content-Range":`bytes */${size}`}});if(!range)return new Response(file,{status:200,headers:{...videoAssetHeaders(name,size,options.etag,options.protectedMedia),"Content-Type":type}});const length=range.end-range.start+1;return new Response(file.slice(range.start,range.end+1),{status:206,headers:{...videoAssetHeaders(name,length,options.etag,options.protectedMedia),"Content-Type":type,"Content-Range":`bytes ${range.start}-${range.end}/${size}`}})}
|
|
1
|
+
import{videoAssetHeaders}from"./index";export function parseByteRange(header,size){const match=/^bytes=(\d*)-(\d*)$/.exec(String(header??"").trim());if(!match||!match[1]&&!match[2])return null;if(!match[1]){const length=Math.min(Number(match[2]),size);return length>0?{start:size-length,end:size-1}:"unsatisfiable"}const start=Number(match[1]);if(start>=size)return"unsatisfiable";const end=match[2]?Math.min(Number(match[2]),size-1):size-1;return end>=start?{start,end}:"unsatisfiable"}const VIDEO_TYPES={mp4:"video/mp4",m4v:"video/mp4",mov:"video/quicktime",webm:"video/webm",m3u8:"application/vnd.apple.mpegurl",mpd:"application/dash+xml",m4s:"video/iso.segment",vtt:"text/vtt"};export function videoContentType(name){return VIDEO_TYPES[name.split(/[?#]/,1)[0].split(".").pop()?.toLowerCase()||""]||"application/octet-stream"}export function videoFileResponse(file,name,options={}){const size=file.size;const type=options.contentType||videoContentType(name);const range=parseByteRange(options.range,size);if(range==="unsatisfiable")return new Response(null,{status:416,headers:{"Content-Range":`bytes */${size}`}});if(!range)return new Response(file,{status:200,headers:{...videoAssetHeaders(name,size,options.etag,options.protectedMedia,options.cacheControl),"Content-Type":type}});const length=range.end-range.start+1;return new Response(file.slice(range.start,range.end+1),{status:206,headers:{...videoAssetHeaders(name,length,options.etag,options.protectedMedia,options.cacheControl),"Content-Type":type,"Content-Range":`bytes ${range.start}-${range.end}/${size}`}})}
|
package/dist/index.d.ts
CHANGED
|
@@ -11,7 +11,14 @@ export declare function videoResponseHeaders(bytes: number, etag: string, conten
|
|
|
11
11
|
export declare function signVideoAsset(path: string, expires: number, secret: string): string;
|
|
12
12
|
export declare function verifyVideoAsset(path: string, expires: number, signature: string, secret: string, now?: number): boolean;
|
|
13
13
|
export declare function createProtectedVideoPlaylist(segments: VideoSegment[], protection?: VideoHlsProtection): Promise<ProtectedVideoPlaylist>;
|
|
14
|
-
|
|
14
|
+
/**
|
|
15
|
+
* Headers for a stored video asset. A manifest of protected media is never
|
|
16
|
+
* stored; a protected media file is cached by the browser only (`private`):
|
|
17
|
+
* a shared cache or CDN must not keep what the app's access check guards, and
|
|
18
|
+
* one that does answered a `Range` probe with the whole file, which iOS Safari
|
|
19
|
+
* refuses to play. `cacheControl` replaces the computed value.
|
|
20
|
+
*/
|
|
21
|
+
export declare function videoAssetHeaders(path: string, bytes?: number, etag?: string, protectedMedia?: boolean, cacheControl?: string): Record<string, string>;
|
|
15
22
|
export declare interface VideoProfile { width: number, height: number, duration: number, frameRate: number, container: VideoContainer, videoCodec: VideoCodec, audioCodec?: VideoAudioCodec, videoBitrate?: number, hasAudio?: boolean, hdr?: boolean }
|
|
16
23
|
export declare interface VideoRendition { name: string, width: number, height: number, frameRate: number, videoBitrate: number, audioBitrate: number }
|
|
17
24
|
export declare interface VideoCapabilities { videoEncoder: boolean, audioEncoder: boolean, videoCodecs: string[], audioCodecs: string[] }
|
package/dist/index.js
CHANGED
|
@@ -3,4 +3,4 @@ import{createHmac,timingSafeEqual}from"node:crypto";const edges=[240,360,480,540
|
|
|
3
3
|
`}function time(seconds){const ms=Math.round(seconds*1000);return`${String(Math.floor(ms/3600000)).padStart(2,"0")}:${String(Math.floor(ms%3600000/60000)).padStart(2,"0")}:${String(Math.floor(ms%60000/1000)).padStart(2,"0")}.${String(ms%1000).padStart(3,"0")}`}export function createPreviewVtt(cues){let end=0;const lines=["WEBVTT",""];cues.forEach((cue,index)=>{if(cue.startTime<end||cue.endTime<=cue.startTime)throw new TypeError(`Invalid preview cue ${index}`);const sprite=[cue.x,cue.y,cue.width,cue.height].every((value)=>value!==undefined);lines.push(`${time(cue.startTime)} --> ${time(cue.endTime)}`,sprite?`${cue.uri}#xywh=${cue.x},${cue.y},${cue.width},${cue.height}`:cue.uri,"");end=cue.endTime});return lines.join(`
|
|
4
4
|
`)}export function videoResponseHeaders(bytes,etag,contentType){return{"Accept-Ranges":"bytes","Content-Length":String(bytes),"Content-Type":contentType,"Cache-Control":"public, max-age=31536000, immutable",ETag:`"${etag}"`}}export function signVideoAsset(path,expires,secret){return createHmac("sha256",secret).update(`${path}
|
|
5
5
|
${expires}`).digest("base64url")}export function verifyVideoAsset(path,expires,signature,secret,now=Date.now()){if(!Number.isInteger(expires)||expires*1000<=now)return false;const expected=Buffer.from(signVideoAsset(path,expires,secret));const actual=Buffer.from(signature);return expected.length===actual.length&&timingSafeEqual(expected,actual)}function sequenceIv(index){const value=new Uint8Array(16);new DataView(value.buffer).setBigUint64(8,BigInt(index));return value}function hex(value){return[...value].map((byte)=>byte.toString(16).padStart(2,"0")).join("")}async function encryptAes(data,key,iv){if(key.byteLength!==16||iv.byteLength!==16)throw new TypeError("HLS AES-128 keys and IVs must contain 16 bytes");const keyBytes=Uint8Array.from(key);const ivBytes=Uint8Array.from(iv);const dataBytes=Uint8Array.from(data);const cryptoKey=await crypto.subtle.importKey("raw",keyBytes.buffer,{name:"AES-CBC"},false,["encrypt"]);return new Uint8Array(await crypto.subtle.encrypt({name:"AES-CBC",iv:ivBytes.buffer},cryptoKey,dataBytes.buffer))}export async function createProtectedVideoPlaylist(segments,protection){if(!segments.length)throw new TypeError("Video playlist requires segments");if(protection&&/[\r\n"]/.test(protection.keyUri))throw new TypeError("Invalid video key URI");const lines=["#EXTM3U","#EXT-X-VERSION:7",`#EXT-X-TARGETDURATION:${Math.ceil(Math.max(...segments.map((item)=>item.duration)))}`,"#EXT-X-PLAYLIST-TYPE:VOD","#EXT-X-INDEPENDENT-SEGMENTS"];const files={};for(const[index,segment]of segments.entries()){if(!Number.isFinite(segment.duration)||segment.duration<=0||/[\r\n"]/.test(segment.uri))throw new TypeError(`Invalid video segment ${index}`);let data=segment.data;if(protection){const iv=protection.iv?.(index)??sequenceIv(index);data=await encryptAes(data,protection.key,iv);lines.push(`#EXT-X-KEY:METHOD=AES-128,URI="${protection.keyUri}",IV=0x${hex(iv)}`)}lines.push(`#EXTINF:${segment.duration.toFixed(6)},`,segment.uri);files[segment.uri]=data}lines.push("#EXT-X-ENDLIST","");return{playlist:lines.join(`
|
|
6
|
-
`),files,encrypted:!!protection}}export function videoAssetHeaders(path,bytes,etag,protectedMedia=false){const manifest=/\.(?:m3u8|mpd|vtt)$/i.test(path);const
|
|
6
|
+
`),files,encrypted:!!protection}}export function videoAssetHeaders(path,bytes,etag,protectedMedia=false,cacheControl){const manifest=/\.(?:m3u8|mpd|vtt)$/i.test(path);const computed=manifest?protectedMedia?"private, no-store":"public, max-age=5, s-maxage=30":protectedMedia?"private, max-age=31536000, immutable":"public, max-age=31536000, immutable";const headers={"Accept-Ranges":"bytes","Cache-Control":cacheControl||computed,"X-Content-Type-Options":"nosniff"};if(bytes!==undefined)headers["Content-Length"]=String(bytes);if(etag)headers.ETag=`"${etag}"`;return headers}export{parseByteRange,videoContentType,videoFileResponse}from"./files";export{inspectVideo}from"./inspect";export{inspectVideoFile,isFaststart,webReadyProblems}from"./upload";
|
package/package.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"name": "@stacksjs/video",
|
|
3
3
|
"type": "module",
|
|
4
4
|
"sideEffects": false,
|
|
5
|
-
"version": "0.75.
|
|
5
|
+
"version": "0.75.685",
|
|
6
6
|
"description": "Native video delivery planning for Stacks.",
|
|
7
7
|
"author": "Chris Breuer",
|
|
8
8
|
"license": "MIT",
|
|
@@ -37,10 +37,10 @@
|
|
|
37
37
|
"prepublishOnly": "bun run build"
|
|
38
38
|
},
|
|
39
39
|
"dependencies": {
|
|
40
|
-
"@ts-videos/mp4": "^0.
|
|
41
|
-
"@ts-videos/webm": "^0.
|
|
40
|
+
"@ts-videos/mp4": "^0.3.1",
|
|
41
|
+
"@ts-videos/webm": "^0.3.1",
|
|
42
42
|
"ts-video-player": "^0.1.3",
|
|
43
|
-
"ts-videos": "^0.
|
|
43
|
+
"ts-videos": "^0.3.1"
|
|
44
44
|
},
|
|
45
45
|
"devDependencies": {
|
|
46
46
|
"better-dx": "^0.2.39"
|