@stacksjs/video 0.75.668 → 0.75.672
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/README.md +27 -0
- package/dist/browser.d.ts +47 -0
- package/dist/browser.js +1 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +1 -1
- package/dist/inspect.d.ts +1 -0
- package/dist/inspect.js +1 -1
- package/dist/upload.d.ts +37 -0
- package/dist/upload.js +1 -0
- package/package.json +10 -4
package/README.md
CHANGED
|
@@ -94,3 +94,30 @@ const licenseEndpoints = {
|
|
|
94
94
|
```
|
|
95
95
|
|
|
96
96
|
The component serializes these descriptors into `data-media-config` and attaches them to DASH sources, detected by MIME type or a `.mpd` URL (including query strings). Progressive fallback sources remain unchanged. License and certificate routes must authorize the viewer.
|
|
97
|
+
|
|
98
|
+
## Uploads
|
|
99
|
+
|
|
100
|
+
Convert a picked clip on the device, then check what arrived on the server.
|
|
101
|
+
|
|
102
|
+
```ts
|
|
103
|
+
// In the browser. Its own path: nothing server-side comes with it.
|
|
104
|
+
import { prepareVideoUpload } from '@stacksjs/video/browser'
|
|
105
|
+
|
|
106
|
+
const { video, poster, converter } = await prepareVideoUpload(file, {
|
|
107
|
+
onProgress: ratio => bar.set(ratio),
|
|
108
|
+
signal,
|
|
109
|
+
})
|
|
110
|
+
// `video` is an upright H.264/AAC MP4 inside 1280x720 at 30 fps with its index
|
|
111
|
+
// first, and `poster` a JPEG of one frame. Where the browser has no WebCodecs,
|
|
112
|
+
// or cannot read the clip, `video` is the file as picked and `converter` null.
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
```ts
|
|
116
|
+
// On the server: read the file, never the client's word for it.
|
|
117
|
+
import { inspectVideoFile, webReadyProblems } from '@stacksjs/video'
|
|
118
|
+
|
|
119
|
+
const clip = await inspectVideoFile(path) // container, codecs, frame as shown, rotation, faststart
|
|
120
|
+
const converted = clip !== null && webReadyProblems(clip, clip.faststart).length === 0
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
Send large files with upload sessions (`createUploadSessions` in `@stacksjs/storage`, `uploadInParts` in `@stacksjs/browser`): parts are retried one by one, and a dropped connection costs one part instead of the upload.
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/** Whether this browser can convert video at all. Cheap: it only looks for the codecs. */
|
|
2
|
+
export declare function canPrepareVideoUpload(): boolean;
|
|
3
|
+
/**
|
|
4
|
+
* Converts a picked clip for upload, or answers it as it is. Only a
|
|
5
|
+
* cancellation throws.
|
|
6
|
+
*/
|
|
7
|
+
export declare function prepareVideoUpload(file: Blob, options?: PrepareVideoUploadOptions): Promise<PreparedVideoUpload>;
|
|
8
|
+
/**
|
|
9
|
+
* The browser half of a video upload: make a picked clip ready to send.
|
|
10
|
+
*
|
|
11
|
+
* A phone records 4K HEVC at 60 frames a second, sideways with a rotation
|
|
12
|
+
* flag, sometimes in HDR: 400 MB for two minutes that half the web cannot
|
|
13
|
+
* play. `prepareVideoUpload` re-encodes it on the device, before anything is
|
|
14
|
+
* sent, into what every player takes: an upright H.264 and AAC MP4 inside
|
|
15
|
+
* 1280 by 720 at 30 frames a second, its index at the front so it plays as it
|
|
16
|
+
* arrives, with a JPEG poster of the same shape. Around a tenth of the bytes.
|
|
17
|
+
*
|
|
18
|
+
* It uses the browser's own codecs (WebCodecs, through ts-videos) and never
|
|
19
|
+
* fails an upload: where the browser cannot do it, or the clip is one it
|
|
20
|
+
* cannot read, the original comes back untouched with the reason, and the
|
|
21
|
+
* caller sends that.
|
|
22
|
+
*
|
|
23
|
+
* Import this file by its own path (`@stacksjs/video/browser`). It pulls in
|
|
24
|
+
* nothing from the server side of this package, and loads the encoder only
|
|
25
|
+
* when a clip is actually prepared.
|
|
26
|
+
*/
|
|
27
|
+
export declare interface PrepareVideoUploadOptions {
|
|
28
|
+
maxLongEdge?: number
|
|
29
|
+
maxShortEdge?: number
|
|
30
|
+
maxFrameRate?: number
|
|
31
|
+
videoBitrate?: number
|
|
32
|
+
poster?: boolean
|
|
33
|
+
maxOutputBytes?: number
|
|
34
|
+
signal?: AbortSignal
|
|
35
|
+
onProgress?: (ratio: number) => void
|
|
36
|
+
}
|
|
37
|
+
export declare interface PreparedVideoUpload {
|
|
38
|
+
video: Blob
|
|
39
|
+
poster?: Blob
|
|
40
|
+
converter: 'webcodecs' | null
|
|
41
|
+
reason?: 'unsupported' | 'already-ready' | 'too-large' | 'failed'
|
|
42
|
+
cause?: unknown
|
|
43
|
+
width?: number
|
|
44
|
+
height?: number
|
|
45
|
+
duration?: number
|
|
46
|
+
sourceBytes: number
|
|
47
|
+
}
|
package/dist/browser.js
ADDED
|
@@ -0,0 +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");try{const{prepareVideoForUpload}=await import("ts-videos/native-transcode");const result=await prepareVideoForUpload(file,{maxLongEdge:options.maxLongEdge,maxShortEdge:options.maxShortEdge,maxFrameRate:options.maxFrameRate,videoBitrate:options.videoBitrate,poster:options.poster??true,maxOutputBytes:options.maxOutputBytes,signal:options.signal,onProgress:options.onProgress?(progress)=>options.onProgress(progress.ratio):undefined});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)}}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
export type { ByteRange, VideoFileResponseOptions } from './files';
|
|
2
2
|
export type { VideoInspection } from './inspect';
|
|
3
|
+
export type { InspectedVideoFile, WebReadyLimits } from './upload';
|
|
3
4
|
export declare function deriveVideoLadder(profile: VideoProfile, maximum?: number): VideoRendition[];
|
|
4
5
|
export declare function video(source: string): VideoBuilder;
|
|
5
6
|
export declare function processVideoPlan(plan: VideoPlan, options?: VideoProcessOptions): Promise<ProcessedVideoDelivery>;
|
|
@@ -44,3 +45,4 @@ export declare class VideoBuilder {
|
|
|
44
45
|
}
|
|
45
46
|
export { parseByteRange, videoContentType, videoFileResponse } from './files';
|
|
46
47
|
export { inspectVideo } from './inspect';
|
|
48
|
+
export { inspectVideoFile, isFaststart, webReadyProblems } from './upload';
|
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 headers={"Accept-Ranges":"bytes","Cache-Control":protectedMedia&&manifest?"private, no-store":manifest?"public, max-age=5, s-maxage=30":"public, max-age=31536000, immutable","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";
|
|
6
|
+
`),files,encrypted:!!protection}}export function videoAssetHeaders(path,bytes,etag,protectedMedia=false){const manifest=/\.(?:m3u8|mpd|vtt)$/i.test(path);const headers={"Accept-Ranges":"bytes","Cache-Control":protectedMedia&&manifest?"private, no-store":manifest?"public, max-age=5, s-maxage=30":"public, max-age=31536000, immutable","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/inspect.d.ts
CHANGED
package/dist/inspect.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Mp4InputFormat,MovInputFormat}from"@ts-videos/mp4";import{WebmInputFormat}from"@ts-videos/webm";import{BufferSource,Input}from"ts-videos";const VIDEO_CODECS={h264:"h264",avc:"h264",avc1:"h264",h265:"h265",hevc:"h265",hvc1:"h265",hev1:"h265",vp8:"vp8",vp9:"vp9",av1:"av1",prores:"prores"};const AUDIO_CODECS={aac:"aac",mp3:"mp3",opus:"opus",vorbis:"vorbis",flac:"flac",alac:"alac",ac3:"ac3",eac3:"eac3"};export async function inspectVideo(bytes){const data=bytes instanceof Uint8Array?bytes:new Uint8Array(bytes);const input=new Input({source:new BufferSource(data),formats:[new Mp4InputFormat,new MovInputFormat,new WebmInputFormat]});try{const track=await input.getPrimaryVideoTrack();if(!track)return null;const audio=await input.getPrimaryAudioTrack().catch(()=>null);const format=await input.getFormatName().catch(()=>"");const duration=await input.getDuration().catch(()=>Number.NaN);const container=format==="webm"?"webm":"mp4";
|
|
1
|
+
import{Mp4InputFormat,MovInputFormat}from"@ts-videos/mp4";import{WebmInputFormat}from"@ts-videos/webm";import{BufferSource,Input}from"ts-videos";const VIDEO_CODECS={h264:"h264",avc:"h264",avc1:"h264",h265:"h265",hevc:"h265",hvc1:"h265",hev1:"h265",vp8:"vp8",vp9:"vp9",av1:"av1",prores:"prores"};const AUDIO_CODECS={aac:"aac",mp3:"mp3",opus:"opus",vorbis:"vorbis",flac:"flac",alac:"alac",ac3:"ac3",eac3:"eac3"};export async function inspectVideo(bytes){const data=bytes instanceof Uint8Array?bytes:new Uint8Array(bytes);const input=new Input({source:new BufferSource(data),formats:[new Mp4InputFormat,new MovInputFormat,new WebmInputFormat]});try{const track=await input.getPrimaryVideoTrack();if(!track)return null;const audio=await input.getPrimaryAudioTrack().catch(()=>null);const format=await input.getFormatName().catch(()=>"");const duration=await input.getDuration().catch(()=>Number.NaN);const container=format==="webm"?"webm":"mp4";const rotation=track.rotation??0;const quarter=rotation===90||rotation===270;const stored={width:track.displayWidth||track.width,height:track.displayHeight||track.height};return{format,container,width:quarter?stored.height:stored.width,height:quarter?stored.width:stored.height,rotation,duration:Number.isFinite(duration)&&duration>0?Math.round(duration*1000)/1000:0,frameRate:track.frameRate&&track.frameRate>0?track.frameRate:30,videoCodec:VIDEO_CODECS[String(track.codec).toLowerCase()]??"unknown",...audio?{audioCodec:AUDIO_CODECS[String(audio.codec).toLowerCase()]??"unknown"}:{},hasAudio:!!audio}}catch{return null}finally{await input.close().catch(()=>{})}}
|
package/dist/upload.d.ts
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import type { VideoInspection } from './inspect';
|
|
2
|
+
/**
|
|
3
|
+
* The server half of a video upload: what a file that arrived actually is.
|
|
4
|
+
*
|
|
5
|
+
* A device may convert a clip before sending it (`@stacksjs/video/browser`)
|
|
6
|
+
* and say so. Nothing a client says is taken on trust: these read the file.
|
|
7
|
+
*/
|
|
8
|
+
/**
|
|
9
|
+
* Whether an MP4 or QuickTime file has its index (moov) before its media
|
|
10
|
+
* (mdat), read from the top-level boxes alone. Such a file starts playing
|
|
11
|
+
* before it has arrived; the other kind must be fetched to its end first.
|
|
12
|
+
* The first megabyte of a file is enough to answer. A WebM, or bytes that are
|
|
13
|
+
* not boxes, are false.
|
|
14
|
+
*/
|
|
15
|
+
export declare function isFaststart(bytes: Uint8Array): boolean;
|
|
16
|
+
/**
|
|
17
|
+
* Why a file is not what `prepareVideoUpload` makes, or an empty list when it
|
|
18
|
+
* is: an MP4 with H.264 video, AAC or no sound, inside the box either way up,
|
|
19
|
+
* with its index first. A client's claim to have converted a clip is worth
|
|
20
|
+
* exactly this check.
|
|
21
|
+
*/
|
|
22
|
+
export declare function webReadyProblems(video: Pick<VideoInspection, 'format' | 'videoCodec' | 'audioCodec' | 'hasAudio' | 'width' | 'height'>, faststart: boolean, limits?: WebReadyLimits): string[];
|
|
23
|
+
/**
|
|
24
|
+
* Reads what a video file on this machine is without holding it in memory:
|
|
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.
|
|
28
|
+
*/
|
|
29
|
+
export declare function inspectVideoFile(path: string): Promise<InspectedVideoFile | null>;
|
|
30
|
+
export declare interface WebReadyLimits {
|
|
31
|
+
maxLongEdge?: number
|
|
32
|
+
maxShortEdge?: number
|
|
33
|
+
}
|
|
34
|
+
export declare interface InspectedVideoFile extends VideoInspection {
|
|
35
|
+
bytes: number
|
|
36
|
+
faststart: boolean
|
|
37
|
+
}
|
package/dist/upload.js
ADDED
|
@@ -0,0 +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}}
|
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.672",
|
|
6
6
|
"description": "Native video delivery planning for Stacks.",
|
|
7
7
|
"author": "Chris Breuer",
|
|
8
8
|
"license": "MIT",
|
|
@@ -17,6 +17,12 @@
|
|
|
17
17
|
"types": "./dist/index.d.ts",
|
|
18
18
|
"bun": "./dist/index.js",
|
|
19
19
|
"import": "./dist/index.js"
|
|
20
|
+
},
|
|
21
|
+
"./*": {
|
|
22
|
+
"types": "./dist/*.d.ts",
|
|
23
|
+
"bun": "./dist/*.js",
|
|
24
|
+
"import": "./dist/*.js",
|
|
25
|
+
"default": "./dist/*.js"
|
|
20
26
|
}
|
|
21
27
|
},
|
|
22
28
|
"module": "dist/index.js",
|
|
@@ -31,10 +37,10 @@
|
|
|
31
37
|
"prepublishOnly": "bun run build"
|
|
32
38
|
},
|
|
33
39
|
"dependencies": {
|
|
34
|
-
"@ts-videos/mp4": "^0.
|
|
35
|
-
"@ts-videos/webm": "^0.
|
|
40
|
+
"@ts-videos/mp4": "^0.2.2",
|
|
41
|
+
"@ts-videos/webm": "^0.2.2",
|
|
36
42
|
"ts-video-player": "^0.1.3",
|
|
37
|
-
"ts-videos": "^0.
|
|
43
|
+
"ts-videos": "^0.2.2"
|
|
38
44
|
},
|
|
39
45
|
"devDependencies": {
|
|
40
46
|
"better-dx": "^0.2.39"
|