@stacksjs/video 0.75.735 → 0.75.755

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/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import{createHmac,timingSafeEqual}from"node:crypto";const edges=[240,360,480,540,720,1080,1440,2160];const even=(value)=>Math.max(2,Math.round(value/2)*2);function validate(profile){for(const[name,value]of Object.entries({width:profile.width,height:profile.height,duration:profile.duration,frameRate:profile.frameRate})){if(!Number.isFinite(value)||value<=0)throw new TypeError(`Video ${name} must be positive`)}}export function deriveVideoLadder(profile,maximum){validate(profile);const short=Math.min(profile.width,profile.height);const limit=Math.min(short,maximum??short);const targets=edges.filter((edge)=>edge<=limit);if(!targets.includes(limit))targets.push(limit);return[...new Set(targets)].sort((a,b)=>a-b).map((edge)=>{const scale=edge/short;const width=even(profile.width*scale);const height=even(profile.height*scale);const rate=Math.round(width*height*Math.min(60,profile.frameRate)*0.075*(profile.frameRate>30?Math.min(2,profile.frameRate/30):1)*(profile.hdr?1.25:1)/1000)*1000;return{name:`${edge}p`,width,height,frameRate:profile.frameRate,videoBitrate:Math.max(250000,Math.min(profile.videoBitrate??1/0,rate)),audioBitrate:profile.hasAudio===false?0:width>=1280?192000:128000}}).filter((item,index,all)=>item.width<=profile.width&&item.height<=profile.height&&all.findIndex((value)=>value.width===item.width&&value.height===item.height)===index)}export class VideoBuilder{source;inspected;formats=["mp4","webm"];streams=["hls","dash"];maximum;capabilities={videoEncoder:false,audioEncoder:false,videoCodecs:[],audioCodecs:[]};constructor(source){this.source=source}profile(value){validate(value);this.inspected=value;return this}ladder(value){if(value!=="auto"&&(!Number.isInteger(value)||value<=0))throw new TypeError("Video ladder height must be positive");this.maximum=value==="auto"?undefined:value;return this}output(formats){if(!formats.length)throw new TypeError("Video formats are required");this.formats=[...new Set(formats)];return this}streaming(formats){this.streams=[...new Set(formats)];return this}runtime(value){this.capabilities=value;return this}generate(){if(!this.inspected)throw new Error("Video inspection is required; pass its profile with .profile()");const profile=this.inspected;const renditions=deriveVideoLadder(profile,this.maximum);const outputs=this.formats.map((container)=>{const videoCodec=container==="mp4"?"h264":"vp9";const audioCodec=profile.hasAudio===false?undefined:container==="mp4"?"aac":"opus";const original=renditions.length===1&&renditions[0].width===profile.width&&renditions[0].height===profile.height;const copy=original&&profile.container===container&&profile.videoCodec===videoCodec&&(!audioCodec||profile.audioCodec===audioCodec);const available=copy||this.capabilities.videoEncoder&&this.capabilities.videoCodecs.includes(videoCodec)&&(!audioCodec||this.capabilities.audioEncoder&&this.capabilities.audioCodecs.includes(audioCodec));return{container,videoCodec,audioCodec,action:copy?"copy":"transcode",available,reason:available?undefined:`Native ${videoCodec}${audioCodec?`/${audioCodec}`:""} encoding is unavailable`}});const segmentDuration=profile.duration<=30?2:profile.duration<=600?4:6;return{source:this.source,profile,renditions,outputs,streaming:this.streams,segmentDuration,keyframeInterval:Math.max(1,Math.round(profile.frameRate*segmentDuration))}}async process(options={}){return processVideoPlan(this.generate(),options)}}export function video(source){return new VideoBuilder(source)}export async function processVideoPlan(plan,options={}){assertVideoPlanExecutable(plan);const{createVideoDeliveryPipeline}=await import("ts-videos/delivery-pipeline");return createVideoDeliveryPipeline(plan.source,{source:plan.profile,renditions:plan.renditions,outputs:plan.outputs,streaming:plan.streaming,segmentDuration:plan.segmentDuration,keyframeInterval:plan.keyframeInterval},options)}export function assertVideoPlanExecutable(plan){const missing=plan.outputs.filter((value)=>!value.available);if(missing.length)throw new Error(missing.map((value)=>`${value.container}: ${value.reason}`).join("; "))}export function createHlsMaster(plan,uri){const lines=["#EXTM3U","#EXT-X-VERSION:7","#EXT-X-INDEPENDENT-SEGMENTS"];const output=plan.outputs.find((value)=>value.container==="mp4");for(const item of plan.renditions){lines.push(`#EXT-X-STREAM-INF:BANDWIDTH=${item.videoBitrate+item.audioBitrate},AVERAGE-BANDWIDTH=${Math.round((item.videoBitrate+item.audioBitrate)*0.9)},RESOLUTION=${item.width}x${item.height},FRAME-RATE=${item.frameRate.toFixed(3)},CODECS="${output?.videoCodec??plan.profile.videoCodec}${output?.audioCodec?`,${output.audioCodec}`:""}"`);lines.push(uri(item))}return`${lines.join(`
2
2
  `)}
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
- `)}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}
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(!Number.isFinite(cue.startTime)||!Number.isFinite(cue.endTime)||cue.startTime<end||cue.endTime<=cue.startTime)throw new TypeError(`Invalid preview cue ${index}`);if(/[\r\n]/.test(cue.uri))throw new TypeError(`Invalid preview cue URI at ${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
+ `)}export function videoResponseHeaders(bytes,etag,contentType){if(/[\r\n"]/.test(etag)||/[\r\n]/.test(contentType))throw new TypeError("Invalid video response header value");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
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/dist/upload.d.ts CHANGED
@@ -23,8 +23,9 @@ export declare function webReadyProblems(video: Pick<VideoInspection, 'format' |
23
23
  /**
24
24
  * Reads what a video file on this machine is without holding it in memory:
25
25
  * its first 8 MB, which contain the whole index of a faststart file, and the
26
- * rest only when the index turns out to be at the end. Null when it holds no
27
- * video. Made for a finished upload session, which is a path, not bytes.
26
+ * rest only when the index turns out to be at the end (capped at 128 MB). Null
27
+ * when it holds no video. Made for a finished upload session, which is a path,
28
+ * not bytes.
28
29
  */
29
30
  export declare function inspectVideoFile(path: string): Promise<InspectedVideoFile | null>;
30
31
  export declare interface WebReadyLimits {
package/dist/upload.js CHANGED
@@ -1 +1 @@
1
- import{inspectVideo}from"./inspect";export function isFaststart(bytes){const view=new DataView(bytes.buffer,bytes.byteOffset,bytes.byteLength);let offset=0;while(offset+8<=bytes.byteLength){let size=view.getUint32(offset);const type=String.fromCharCode(bytes[offset+4],bytes[offset+5],bytes[offset+6],bytes[offset+7]);if(type==="moov")return true;if(type==="mdat")return false;if(size===1){if(offset+16>bytes.byteLength)return false;size=Number(view.getBigUint64(offset+8))}if(size<8)return false;offset+=size}return false}export function webReadyProblems(video,faststart,limits={}){const long=Math.max(video.width||0,video.height||0);const short=Math.min(video.width||0,video.height||0);return[video.format!=="mp4"&&`container ${video.format}`,video.videoCodec!=="h264"&&`video ${video.videoCodec}`,video.hasAudio&&video.audioCodec!=="aac"&&`audio ${video.audioCodec}`,(short<=0||long>(limits.maxLongEdge??1280)||short>(limits.maxShortEdge??720))&&`size ${video.width}x${video.height}`,!faststart&&"not faststart"].filter((problem)=>typeof problem==="string")}const HEAD_BYTES=8*1024*1024;export async function inspectVideoFile(path){const file=Bun.file(path);if(!await file.exists())return null;const head=new Uint8Array(await file.slice(0,HEAD_BYTES).arrayBuffer());const whole=file.size<=HEAD_BYTES;const inspection=await inspectVideo(head)??(whole?null:await inspectVideo(new Uint8Array(await file.arrayBuffer())));if(!inspection)return null;const boxes=inspection.format==="mp4"||inspection.format==="mov";return{...inspection,bytes:file.size,faststart:boxes?isFaststart(head):false}}
1
+ import{inspectVideo}from"./inspect";export function isFaststart(bytes){const view=new DataView(bytes.buffer,bytes.byteOffset,bytes.byteLength);let offset=0;while(offset+8<=bytes.byteLength){let size=view.getUint32(offset);const type=String.fromCharCode(bytes[offset+4],bytes[offset+5],bytes[offset+6],bytes[offset+7]);if(type==="moov")return true;if(type==="mdat")return false;if(size===1){if(offset+16>bytes.byteLength)return false;size=Number(view.getBigUint64(offset+8))}if(size<8)return false;offset+=size}return false}export function webReadyProblems(video,faststart,limits={}){const long=Math.max(video.width||0,video.height||0);const short=Math.min(video.width||0,video.height||0);return[video.format!=="mp4"&&`container ${video.format}`,video.videoCodec!=="h264"&&`video ${video.videoCodec}`,video.hasAudio&&video.audioCodec!=="aac"&&`audio ${video.audioCodec}`,(short<=0||long>(limits.maxLongEdge??1280)||short>(limits.maxShortEdge??720))&&`size ${video.width}x${video.height}`,!faststart&&"not faststart"].filter((problem)=>typeof problem==="string")}const HEAD_BYTES=8*1024*1024;const MAX_FALLBACK_INSPECT_BYTES=128*1024*1024;export async function inspectVideoFile(path){const file=Bun.file(path);if(!await file.exists())return null;const head=new Uint8Array(await file.slice(0,HEAD_BYTES).arrayBuffer());const whole=file.size<=HEAD_BYTES;let inspection=await inspectVideo(head);if(!inspection&&!whole&&file.size<=MAX_FALLBACK_INSPECT_BYTES)inspection=await inspectVideo(new Uint8Array(await file.arrayBuffer()));if(!inspection)return null;const boxes=inspection.format==="mp4"||inspection.format==="mov";return{...inspection,bytes:file.size,faststart:boxes?isFaststart(head):false}}
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.735",
5
+ "version": "0.75.755",
6
6
  "description": "Native video delivery planning for Stacks.",
7
7
  "author": "Chris Breuer",
8
8
  "license": "MIT",
@@ -37,12 +37,12 @@
37
37
  "prepublishOnly": "bun run build"
38
38
  },
39
39
  "dependencies": {
40
- "@ts-videos/mp4": "^0.3.1",
41
- "@ts-videos/webm": "^0.3.1",
40
+ "@ts-videos/mp4": "^0.5.0",
41
+ "@ts-videos/webm": "^0.5.0",
42
42
  "ts-video-player": "^0.1.3",
43
- "ts-videos": "^0.3.1"
43
+ "ts-videos": "^0.5.0"
44
44
  },
45
45
  "devDependencies": {
46
- "better-dx": "^0.2.39"
46
+ "better-dx": "^0.2.41"
47
47
  }
48
48
  }