@ahmedrowaihi/mediabunny 1.65.2-beta.698 → 1.65.2-beta.699
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/bundles/mediabunny.cjs +8 -4
- package/dist/bundles/mediabunny.min.cjs +2 -2
- package/dist/bundles/mediabunny.min.mjs +2 -2
- package/dist/bundles/mediabunny.mjs +8 -4
- package/dist/bundles/mediabunny.node.cjs +8 -4
- package/dist/mediabunny.d.ts +16 -0
- package/dist/modules/src/output-format.d.ts +16 -0
- package/dist/modules/src/output-format.d.ts.map +1 -1
- package/dist/modules/src/output-format.js +3 -0
- package/dist/modules/src/segment-pipeline-muxer.d.ts.map +1 -1
- package/dist/modules/src/segment-pipeline-muxer.js +11 -4
- package/dist/modules/src/tsconfig.tsbuildinfo +1 -1
- package/package.json +1 -1
- package/src/output-format.ts +19 -0
- package/src/segment-pipeline-muxer.ts +12 -4
|
@@ -52290,7 +52290,8 @@ ${cue.notes ?? ""}`;
|
|
|
52290
52290
|
*/
|
|
52291
52291
|
chooseSegmentCut(playlist, videoTrack, audioTrack, audioHasGoneQuiet) {
|
|
52292
52292
|
assert(playlist.currentSegmentStartTimestamp !== null);
|
|
52293
|
-
const
|
|
52293
|
+
const statedBoundary = this.options.nextSegmentBoundary?.(playlist.currentSegmentStartTimestamp) ?? null;
|
|
52294
|
+
const currentSegmentEndTimestamp = statedBoundary ?? playlist.currentSegmentStartTimestamp + this.targetSegmentDuration;
|
|
52294
52295
|
if (playlist.segmentGridOrigin === null || playlist.nextSegmentId === 1) {
|
|
52295
52296
|
playlist.segmentGridOrigin = playlist.currentSegmentStartTimestamp;
|
|
52296
52297
|
}
|
|
@@ -52298,7 +52299,7 @@ ${cue.notes ?? ""}`;
|
|
|
52298
52299
|
const elapsedGrids = Math.round(
|
|
52299
52300
|
(playlist.currentSegmentStartTimestamp - gridOrigin) / this.targetSegmentDuration
|
|
52300
52301
|
);
|
|
52301
|
-
const gridBoundary = gridOrigin + (elapsedGrids + 1) * this.targetSegmentDuration;
|
|
52302
|
+
const gridBoundary = statedBoundary ?? gridOrigin + (elapsedGrids + 1) * this.targetSegmentDuration;
|
|
52302
52303
|
let videoEndIndex = 0;
|
|
52303
52304
|
let audioEndIndex = 0;
|
|
52304
52305
|
if (videoTrack && (!videoTrack.closed || videoTrack.packets.length > 0)) {
|
|
@@ -52381,8 +52382,8 @@ ${cue.notes ?? ""}`;
|
|
|
52381
52382
|
const after = audioTrack.packets.findIndex((x) => x.timestamp >= gridBoundary);
|
|
52382
52383
|
assert(after !== -1);
|
|
52383
52384
|
const earlier = audioTrack.packets[after - 1];
|
|
52384
|
-
const
|
|
52385
|
-
audioEndIndex = Math.max(
|
|
52385
|
+
const chosen = statedBoundary === null && earlier !== void 0 && gridBoundary - earlier.timestamp <= audioTrack.packets[after].timestamp - gridBoundary ? after - 1 : after;
|
|
52386
|
+
audioEndIndex = Math.max(chosen, 1);
|
|
52386
52387
|
}
|
|
52387
52388
|
}
|
|
52388
52389
|
return { videoEndIndex, audioEndIndex };
|
|
@@ -53861,6 +53862,9 @@ ${cue.text}
|
|
|
53861
53862
|
if (options.targetDuration !== void 0 && (typeof options.targetDuration !== "number" || options.targetDuration <= 0)) {
|
|
53862
53863
|
throw new TypeError("options.targetDuration, when provided, must be a positive number.");
|
|
53863
53864
|
}
|
|
53865
|
+
if (options.nextSegmentBoundary !== void 0 && typeof options.nextSegmentBoundary !== "function") {
|
|
53866
|
+
throw new TypeError("options.nextSegmentBoundary, when provided, must be a function.");
|
|
53867
|
+
}
|
|
53864
53868
|
if (options.partDuration !== void 0 && (!Number.isFinite(options.partDuration) || options.partDuration <= 0)) {
|
|
53865
53869
|
throw new TypeError("options.partDuration, when provided, must be a positive finite number.");
|
|
53866
53870
|
}
|
|
@@ -66,14 +66,14 @@ ${n.notes??""}`,d=this.createInternalChunk(c,n.timestamp,n.duration,"key",u.trim
|
|
|
66
66
|
`,n=!1,i=[];for(let o of this.host.playlistDeclarations)for(let l of o.playlist.tracks)for(let c of Hk(l))i.includes(c)||i.push(c);if(i.length>0){t+=`
|
|
67
67
|
`;for(let o of i)t+=`#EXT-X-MEDIA:TYPE=CLOSED-CAPTIONS,GROUP-ID="${zk}",NAME="${o}",INSTREAM-ID="${o}",AUTOSELECT=YES
|
|
68
68
|
`}let a={lastGroupId:null,trackCount:0,hasDefault:!1};for(let o of this.host.playlistDeclarations)o.groupId===null?(n||(t+=`
|
|
69
|
-
`,n=!0),t+=this.variantTag(o)):t+=this.renditionTag(o,a);this.options.onMaster?.(t);let s=await this.host.acquireMutex();try{let o;if(this.host.numWrittenMasterPlaylists===0)o=await this.host.output._getRootWriter(!0);else{let l=await this.host.output._getTarget({path:e.rootPath,isRoot:!0,mimeType:cr});o=new Br(l,!0),o.start()}o.write(re.encode(t)),await o.flush(),await o.finalize(),this.host.noteMasterPlaylistWritten()}finally{s()}}async tryWriteMasterPlaylist(){b(this.host.isLive);for(let e of this.host.playlists)if(e.writtenSegments.length===0&&!e.done)return;await this.writeMasterPlaylist()}};var oR="subtitles",qk=r=>({...r.track.metadata,closedCaptions:void 0,decoderConfig:r.info.decoderConfig,primingPacket:r.info.primingPacket??void 0}),Gk=r=>({...r.track.metadata,decoderConfig:r.info.decoderConfig,primingPacket:r.info.primingPacket??void 0}),$k=(r,e)=>{let t={output:new pr({format:r,target:e}),videoSource:null,audioSource:null,subtitleSource:null,firstMoofPosition:null,currentFileSize:0};e.on("write",({end:a})=>{t.currentFileSize=Math.max(t.currentFileSize,a)});let n=t.output._muxer;n.minimumFragmentDuration=1/0;let i=n.formatOptions.onMoof;return n.formatOptions.onMoof=(a,s,o)=>{t.firstMoofPosition=s,i?.(a,s,o),n.formatOptions.onMoof=i},t},Xk=async r=>{let e=r.singleFile;return b(e?.fragmentedIsobmffOutput),await e.fragmentedIsobmffOutput.output._muxer.forceFragmentFinalization(),e.fragmentedIsobmffOutput.firstMoofPosition!==null&&!r.initSegment&&(r.initSegment={path:e.path,duration:0,timestamp:0,byteSize:e.fragmentedIsobmffOutput.firstMoofPosition,byteOffset:0,info:null,parts:null},e.nextOffset=e.fragmentedIsobmffOutput.firstMoofPosition),e.fragmentedIsobmffOutput.currentFileSize-e.nextOffset},lR=({metadata:r})=>[r.languageCode??ye,r.name??"",r.disposition?.default??!0,r.disposition?.primary??!1,r.disposition?.forced??!1].join("-"),el=class extends Ke{constructor(t,n,i){if(!(t._target instanceof Je))throw new TypeError("HLS outputs require `OutputOptions.target` to be a PathedTarget.");super(t);this.trackDatas=[];this.firstPacketTimestamp=null;this.isRelativeToUnixEpoch=!1;this.numWrittenMasterPlaylists=0;this.playlists=[];this.playlistDeclarations=[];this.subtitlePlaylists=[];this.subtitleBoundarySource=null;this.options=n,this.targetSegmentDuration=n.targetDuration??2,this.singleFilePerPlaylist=n.singleFilePerPlaylist??!1,this.separateRenditions=n.separateRenditions??!1,this.isLive=n.live??!1,this.maxLiveSegmentCount=n.maxLiveSegmentCount??1/0,this.partDuration=n.partDuration??null,this.mediaTimestampBase=n.mediaTimestampBase??10,this.globalTargetDuration=this.targetSegmentDuration,this.getPlaylistPath=n.getPlaylistPath??(({n:a})=>`playlist-${a}.m3u8`),this.getSegmentPath=n.getSegmentPath??(a=>a.isSingleFile?`segments-${a.playlist.n}${a.format.fileExtension}`:`segment-${a.playlist.n}-${a.n}${a.format.fileExtension}`),this.getInitPath=n.getInitPath??(a=>`init-${a.n}${a.segmentFormat.fileExtension}`),this.manifestEmitters=i(this),this.mediaIsAddressedByItsOwnTimestamps=this.manifestEmitters.some(a=>a.addressesMediaByItsOwnTimestamps)}startInnerOutput(t,n){let i=this.output._metadataTags;return t.setMetadataTags({...i,...n,...i.raw||n?.raw?{raw:{...i.raw,...n?.raw}}:{}}),t.start()}async broadcast(t,...n){for(let i of this.manifestEmitters){let a=i[t];a&&await a.apply(i,n)}}noteMasterPlaylistWritten(){this.numWrittenMasterPlaylists++}acquireMutex(){return this.mutex.acquire()}async start(){let t=await this.mutex.acquire(),n=this.output.tracks.some(m=>m.metadata.isRelativeToUnixEpoch),i=this.output.tracks.some(m=>!m.metadata.isRelativeToUnixEpoch);if(n&&i)throw new Error("All tracks must agree on `relativeToUnixEpoch`: some tracks are relative to the Unix epoch and some are not.");this.isRelativeToUnixEpoch=n;let{groups:a,groupAssignment:s,hasVideo:o}=this.buildRenditionGroups(),{variantStreams:l,unpairedVideoTracks:c,unpairedAudioTracks:u}=this.buildVariantStreams(a,s,o?"video":"audio");this.placeUnpairedTracks("video",c,a,l),this.placeUnpairedTracks("audio",u,a,l),await this.declareGroupRenditions(a);let d=await this.declareSubtitleRenditions();await this.declareVariants(l,d),d.length>0&&(this.subtitleBoundarySource=this.resolveSubtitleBoundarySource()),this.registerDeclaredTracks(),await this.broadcast("onStart"),t()}buildRenditionGroups(){let t=new Map,n=[],i=!1,a=!1,s=!1;for(let o of this.output.tracks){if(o.type==="video"&&(i=!0),o.isSubtitleTrack())continue;let l=new Map;for(let c of this.output.tracks){if(o===c||c.isSubtitleTrack()||!o.canBePairedWith(c))continue;if(o.type===c.type){a||(N._warn(`Illegal pairing of two ${o.type} tracks detected, which is not possible in HLS; treating them as unpaired.`),a=!0);continue}if(o.isVideoTrack()&&o.metadata.hasOnlyKeyPackets||c.isVideoTrack()&&c.metadata.hasOnlyKeyPackets){s||(N._warn("A key-packets-only video track is pairable with another track, which is not possible in HLS; treating them as unpaired."),s=!0);continue}let u=l.get(c.source._codec);u||l.set(c.source._codec,u=[]),u.push(c)}for(let[,c]of l){let u=c.map(f=>f.id).join("-");n.find(f=>f.key===u)||n.push({name:c[0].type+"-"+(n.length+1),key:u,tracks:c,needsEmit:!1,firstNoUri:!1});let m=t.get(o);m||t.set(o,m=[]),m.push(u)}}return{groups:n,groupAssignment:t,hasVideo:i}}buildVariantStreams(t,n,i){let a=[],s=[],o=[];for(let l of this.output.tracks){let c=n.get(l);if(!c){l.type==="video"?s.push(l):l.type==="audio"&&o.push(l);continue}if(b(c.length>0),l.type===i)for(let u of c){let d=t.find(m=>m.key===u);if(b(d),!this.separateRenditions&&c.length===1&&d.tracks.length===1){let m=n.get(d.tracks[0]);if(b(m!==void 0),m.length===1){let f=t.find(p=>p.key===m[0]);if(f.tracks.length===1){b(f.tracks[0]===l),a.push({tracks:[l,d.tracks[0]],linkedGroup:null});continue}}}a.push({tracks:[l],linkedGroup:d}),d.needsEmit=!0}}return{variantStreams:a,unpairedVideoTracks:s,unpairedAudioTracks:o}}placeUnpairedTracks(t,n,i,a){if(n.length===0)return;if(new Set(n.map(lR)).size===1){for(let o of n)a.push({tracks:[o],linkedGroup:null});return}let s={key:n.map(o=>o.id).join("-"),name:t+"-"+(i.length+1),tracks:n,needsEmit:!0,firstNoUri:!0};i.push(s),a.push({tracks:[n[0]],linkedGroup:s})}deduceSegmentFormat(t){let n=[],i=0,a=0,s=0,o=!1,l=null,c=-1/0;for(let u of t)u.isVideoTrack()?(i++,o||=(u.metadata.rotation??0)!==0||!!u.metadata.flip||!!u.metadata.transformationMatrix):u.isAudioTrack()?a++:s++,n.push(u.source._codec);for(let u of[Kk,...ot(this.options.segmentFormat)]){let d=u.getSupportedCodecs(),m=u.getSupportedTrackCounts();if(n.some(p=>!d.includes(p))||i<m.video.min||i>m.video.max||a<m.audio.min||a>m.audio.max||s<m.subtitle.min||s>m.subtitle.max)continue;let f=0;o&&u.supportsVideoTransformationMetadata&&f++,f>c&&(l=u,c=f)}return b(l),l}async registerPlaylist(t){let n=t[0].isSubtitleTrack();if(t.some(l=>this.playlists.some(c=>c.tracks.includes(l))))throw new Error("Internal error: track is already registered in a playlist.");let i=this.deduceSegmentFormat(t);i instanceof ws&&i._options.timestampOffset===void 0&&(i=new ws({...i._options,timestampOffset:0}));let a=this.playlists.length+1,s=await this.getPlaylistPath({n:a,tracks:t,segmentFormat:i});cR(s);let o={id:a,path:s,tracks:t,segmentFormat:i,currentSegmentStartTimestamp:null,currentSegmentStartTimestampIsFixed:!1,segmentGridOrigin:null,nextSegmentId:1,initSegment:null,pendingInit:null,indexRange:null,writtenSegments:[],windowDuration:0,peakBitrate:null,averageBitrate:null,mediaSequence:0,done:!1,subtitleBoundaries:n?[]:null,singleFile:null,mutex:new vt,bitrateCache:null};return this.playlists.push(o),n&&this.subtitlePlaylists.push(o),o}async declareGroupRenditions(t){for(let n of t)if(n.needsEmit)for(let i=0;i<n.tracks.length;i++){let a=n.tracks[i],s=this.playlists.find(o=>o.tracks[0].id===a.id);s??=await this.registerPlaylist([a]),this.playlistDeclarations.push({playlist:s,groupId:n.name,noUri:n.firstNoUri&&i===0,references:[]})}}async declareSubtitleRenditions(){let t=[];for(let n of this.output.tracks.filter(i=>i.isSubtitleTrack())){let i={playlist:await this.registerPlaylist([n]),groupId:oR,noUri:!1,references:[]};t.push(i),this.playlistDeclarations.push(i)}return t}async declareVariants(t,n){for(let i of t){let a=this.playlists.find(s=>s.tracks[0].id===i.tracks[0].id);a??=await this.registerPlaylist(i.tracks),this.playlistDeclarations.push({playlist:a,groupId:null,noUri:!1,references:[...i.linkedGroup?this.playlistDeclarations.filter(s=>s.groupId===i.linkedGroup.name):[],...n]})}}resolveSubtitleBoundarySource(){let t=this.playlists.filter(i=>i.subtitleBoundaries===null),n=t.find(i=>i.tracks.some(a=>a.isVideoTrack()))??t[0];if(!n)throw new Error("Subtitle tracks require at least one video or audio track, as subtitle segments are cut on the media segment boundaries. Add a video or audio track.");return n}registerDeclaredTracks(){for(let t of this.output.tracks)t.isVideoTrack()&&t.metadata.decoderConfig?this.getVideoTrackData(t,t.metadata.primingPacket??null,{decoderConfig:t.metadata.decoderConfig}):t.isAudioTrack()&&t.metadata.decoderConfig?this.getAudioTrackData(t,t.metadata.primingPacket??null,{decoderConfig:t.metadata.decoderConfig}):t.isSubtitleTrack()&&this.getSubtitleTrackData(t)}async getMimeType(){return cr}allTracksAreKnown(t){for(let n of t.tracks)if(!n.source._closed&&!this.trackDatas.some(i=>i.track===n))return!1;return!0}async onTrackClose(t){let n=this.trackDatas.find(s=>s.track===t);n&&(n.closed=!0);let i=this.playlists.find(s=>s.tracks.includes(t));b(i);let a=await i.mutex.acquire();try{i.subtitleBoundaries?await this.advanceSubtitlePlaylist(i):await this.advancePlaylist(i)}finally{a()}}getVideoTrackData(t,n,i){let a=this.trackDatas.find(o=>o.track===t);if(a)return a;Vn(i,t.source._codec),b(i),b(i?.decoderConfig);let s=this.playlists.filter(o=>o.tracks.includes(t));return b(s.length===1),a={track:t,packets:[],playlist:s[0],closed:!1,info:{type:"video",decoderConfig:i.decoderConfig,inBandParameterSets:!i.decoderConfig.description||t.metadata.parameterSets==="inBand",primingPacket:n}},this.trackDatas.push(a),a}getAudioTrackData(t,n,i){let a=this.trackDatas.find(o=>o.track===t);if(a)return a;tt(i,t.source._codec),b(i),b(i?.decoderConfig);let s=this.playlists.filter(o=>o.tracks.includes(t));return b(s.length===1),a={track:t,packets:[],playlist:s[0],closed:!1,info:{type:"audio",decoderConfig:i.decoderConfig,primingPacket:n}},this.trackDatas.push(a),a}async addEncodedVideoPacket(t,n,i){let a=this.getVideoTrackData(t,n,i),s=a.playlist,o=await s.mutex.acquire();try{this.validateTimestamp(t,n.timestamp,n.type==="key"),a.packets.push(n),this.firstPacketTimestamp??=n.timestamp,s.currentSegmentStartTimestamp===null?s.currentSegmentStartTimestamp=n.timestamp:s.currentSegmentStartTimestampIsFixed||(s.currentSegmentStartTimestamp=Math.min(s.currentSegmentStartTimestamp,n.timestamp)),await this.advancePlaylist(s)}finally{o()}}async addEncodedAudioPacket(t,n,i){let a=this.getAudioTrackData(t,n,i),s=a.playlist,o=await s.mutex.acquire();try{this.validateTimestamp(t,n.timestamp,n.type==="key"),a.packets.push(n),this.firstPacketTimestamp??=n.timestamp,s.currentSegmentStartTimestamp===null?s.currentSegmentStartTimestamp=n.timestamp:s.currentSegmentStartTimestampIsFixed||(s.currentSegmentStartTimestamp=Math.min(s.currentSegmentStartTimestamp,n.timestamp)),await this.advancePlaylist(s)}finally{o()}}getSubtitleTrackData(t,n){let i=this.trackDatas.find(s=>s.track===t);if(i)return i.info.config??=n?.config??null,i;let a=this.playlists.filter(s=>s.tracks.includes(t));return b(a.length===1),i={track:t,packets:[],playlist:a[0],closed:!1,info:{type:"subtitle",cues:[],config:n?.config??null}},this.trackDatas.push(i),i}async addSubtitleCue(t,n,i){let a=this.getSubtitleTrackData(t,i),s=a.playlist,o=await s.mutex.acquire();try{this.validateTimestamp(t,n.timestamp,!0),a.info.cues.push(n),await this.advanceSubtitlePlaylist(s)}finally{o()}}get maxInterleaveDelta(){return this.options.maxInterleaveDelta??wr}async advancePlaylist(t){if(b(!t.done),!this.allTracksAreKnown(t))return;let n=this.trackDatas.filter(o=>t.tracks.includes(o.track));if(t.currentSegmentStartTimestamp===null){n.every(o=>o.closed)&&await this.onPlaylistDone(t);return}let i=n.find(o=>o.info.type==="video"),a=n.find(o=>o.info.type==="audio"),s=()=>!a||!i||i.packets.length===0?!1:this.quietTrackMayBeSkipped(n,o=>o.packets,o=>o.timestamp);for(;;){let o=this.chooseSegmentCut(t,i,a,s);if(o===null)return;if(o.videoEndIndex===0&&o.audioEndIndex===0){n.every(m=>m.closed)&&await this.onPlaylistDone(t);return}let{segmentInfo:l,relativeSegmentPath:c,fullSegmentPath:u}=await this.openSegmentTarget(t,i,a),d=await this.writeSegmentMedia(t,i,a,o,u);await this.recordSegment(t,n,i,a,{...o,...d,segmentInfo:l,relativeSegmentPath:c}),await this.evictLiveSegments(t)}}chooseSegmentCut(t,n,i,a){b(t.currentSegmentStartTimestamp!==null);let s=t.currentSegmentStartTimestamp+this.targetSegmentDuration;(t.segmentGridOrigin===null||t.nextSegmentId===1)&&(t.segmentGridOrigin=t.currentSegmentStartTimestamp);let o=t.segmentGridOrigin,l=Math.round((t.currentSegmentStartTimestamp-o)/this.targetSegmentDuration),c=o+(l+1)*this.targetSegmentDuration,u=0,d=0;if(n&&(!n.closed||n.packets.length>0)){let m=n.packets.every(g=>g.timestamp<s),f=null,p=null;if(m){if(!n.closed)return null}else for(let g=0;g<n.packets.length;g++){let h=n.packets[g];if(f!==null&&h.timestamp>s)break;g>0&&h.type==="key"&&(f=h,p=g)}if(p!==null){if(u=p,i){let g=i.packets.findIndex(h=>h.timestamp>=f.timestamp);if(g!==-1)d=g;else if(i.closed||a())d=i.packets.length;else return null}}else{if(!n.closed)return null;u=n.packets.length;let g=ky(n.packets,y=>y.timestamp),h=n.packets[g];if(b(h),i)if(h.timestamp<s){let y=i.packets.findIndex(S=>S.timestamp>=s);if(y!==-1)d=y;else if(i.closed||a())d=i.packets.length;else return null}else{let y=i.packets.findIndex(S=>S.timestamp>h.timestamp);if(y!==-1)d=y;else if(i.closed||a())d=i.packets.length;else return null}}}else if(i&&(!i.closed||i.packets.length>0))if(i.packets.every(f=>f.timestamp<c))if(i.closed)d=i.packets.length;else return null;else{let f=i.packets.findIndex(h=>h.timestamp>=c);b(f!==-1);let p=i.packets[f-1],g=p!==void 0&&c-p.timestamp<=i.packets[f].timestamp-c?f-1:f;d=Math.max(g,1)}return{videoEndIndex:u,audioEndIndex:d}}async openSegmentTarget(t,n,i){let a=null,s,o;b(this.output._target instanceof Je);let l=this.output._target;if(this.singleFilePerPlaylist)if(t.singleFile===null){let c={n:t.nextSegmentId,format:t.segmentFormat,isSingleFile:!0,playlist:uu(t),parts:null,isLast:!0};s=await this.getSegmentPath(c),Nf(s),o=Ie(Ie(l.rootPath,t.path),s);let u=await this.output._getTarget({path:o,isRoot:!1,mimeType:t.segmentFormat.mimeType}),d=null;t.segmentFormat._isFragmentedIsobmff()?(d=$k(t.segmentFormat,u),n&&(d.videoSource=new ui(n.track.source._codec),d.output.addVideoTrack(d.videoSource,qk(n))),i&&(d.audioSource=new mi(i.track.source._codec),d.output.addAudioTrack(d.audioSource,Gk(i))),await this.startInnerOutput(d.output)):u._start(),t.singleFile={target:u,path:s,nextOffset:0,info:c,fragmentedIsobmffOutput:d}}else s=t.singleFile.path,o=Ie(Ie(l.rootPath,t.path),s);else a={n:t.nextSegmentId,format:t.segmentFormat,isSingleFile:!1,playlist:uu(t),parts:null,isLast:!1},s=await this.getSegmentPath(a),Nf(s),o=Ie(Ie(l.rootPath,t.path),s),t.nextSegmentId++;return{segmentInfo:a,relativeSegmentPath:s,fullSegmentPath:o}}async writeSegmentMedia(t,n,i,{videoEndIndex:a,audioEndIndex:s},o){let l=0,c=null,u=-1/0,d=[],m=[],f=null,p=null,g=null,h;try{if(t.singleFile?.fragmentedIsobmffOutput)f=t.singleFile.fragmentedIsobmffOutput.output,p=t.singleFile.fragmentedIsobmffOutput.videoSource,g=t.singleFile.fragmentedIsobmffOutput.audioSource;else{if(f=new pr({format:t.segmentFormat,target:new Je(o,async k=>{let T={...k,isRoot:!1};if(k.isRoot)if(t.singleFile){let w=t.singleFile.target.slice(t.singleFile.nextOffset);return w.on("write",({end:A})=>l=Math.max(l,A)),w}else{let w=await this.output._getTarget(T);return c=w,w.on("write",({end:A})=>l=Math.max(l,A)),w}return this.output._getTarget(T)}),initTarget:this.initTargetFor(t)}),n&&(p=new ui(n.track.source._codec),f.addVideoTrack(p,qk(n))),i&&(g=new mi(i.track.source._codec),f.addAudioTrack(g,Gk(i)),!t.segmentFormat.supportsTimestampedMediaData&&s>0)){let k=this.toMediaTimestamp(i.packets[0].timestamp),T=Ya(k),w=new Uint8Array(Er.length+1+8);w.set(re.encode(Er),0);let A=z(w);A.setUint32(Er.length+1,Math.floor(T/2**32)),A.setUint32(Er.length+5,T%2**32),h={raw:{PRIV:w}}}await this.startInnerOutput(f,h)}let y=f._muxer,S=y instanceof ps&&y.isFragmented?this.options.partDuration:void 0;u=S===void 0?await this.addSegmentPackets(n,i,{videoEndIndex:a,audioEndIndex:s},p,g):await this.addSegmentPacketsInParts(n,i,{videoEndIndex:a,audioEndIndex:s},p,g,y,S,d,m),t.singleFile?.fragmentedIsobmffOutput?l=await Xk(t):await f.finalize()}catch(y){throw await f?.cancel(),y}return{segmentSize:l,maxEndTimestamp:u,partStarts:d,partEnds:m,outputTarget:c}}async recordSegment(t,n,i,a,{videoEndIndex:s,audioEndIndex:o,segmentInfo:l,relativeSegmentPath:c,segmentSize:u,maxEndTimestamp:d,partStarts:m,partEnds:f,outputTarget:p}){b(t.currentSegmentStartTimestamp!==null),s>0&&(b(i),i.packets.splice(0,s)),o>0&&(b(a),a.packets.splice(0,o));let g=1/0;i&&i.packets.length>0&&(g=i.packets[0].timestamp),a&&a.packets.length>0&&(g=Math.min(g,a.packets[0].timestamp));let h=g<1/0?g:d;b(Number.isFinite(h));let y=h-t.currentSegmentStartTimestamp;b(y>=0);let S=null;if(m.length>0){let k=t.singleFile?.fragmentedIsobmffOutput?t.singleFile.nextOffset:0,T=[0,...f.map(A=>A-k),u],w=t.currentSegmentStartTimestamp;S=m.map((A,x)=>({offset:T[x],size:T[x+1]-T[x],duration:(m[x+1]?.timestamp??h)-(x===0?w:A.timestamp),independent:A.independent}))}if(l&&(b(p),l.parts=S,l.isLast=dR(n),await this.drainPendingInit(t),await this.options.onSegment?.(p,l)),t.windowDuration+=y,t.writtenSegments.push({path:c,duration:y,timestamp:t.currentSegmentStartTimestamp,byteSize:u,byteOffset:t.singleFile?t.singleFile.nextOffset:null,info:l??null,parts:S}),this.globalTargetDuration=Math.max(this.globalTargetDuration,y),t===this.subtitleBoundarySource){let k={timestamp:t.currentSegmentStartTimestamp,duration:y};for(let T of this.subtitlePlaylists){T.subtitleBoundaries.push(k);let w=await T.mutex.acquire();try{await this.advanceSubtitlePlaylist(T)}finally{w()}}}t.currentSegmentStartTimestamp=h,t.currentSegmentStartTimestampIsFixed=!0,t.singleFile&&(t.singleFile.nextOffset+=u)}async addSegmentPackets(t,n,{videoEndIndex:i,audioEndIndex:a},s,o){let l=-1/0;if(t){b(s);let c={decoderConfig:t.info.decoderConfig};for(let u=0;u<i;u++){let d=t.packets[u];await s.add(this.toMediaPacket(d),c),l=Math.max(l,d.timestamp+d.duration)}}if(n){b(o);let c={decoderConfig:n.info.decoderConfig};for(let u=0;u<a;u++){let d=n.packets[u];await o.add(this.toMediaPacket(d),c),l=Math.max(l,d.timestamp+d.duration)}}return l}async addSegmentPacketsInParts(t,n,{videoEndIndex:i,audioEndIndex:a},s,o,l,c,u,d){let m=-1/0;b(l instanceof ps);let f=t&&{decoderConfig:t.info.decoderConfig},p=n&&{decoderConfig:n.info.decoderConfig},g=0,h=0;for(;g<i||h<a;){let y=g<i?t.packets[g]:null,S=h<a?n.packets[h]:null,k=y!==null&&(S===null||y.timestamp<=S.timestamp),T=k?y:S,w=u.at(-1),A=w!==void 0&&(k||!t)&&T.timestamp+T.duration>w.timestamp+c+1e-6;if(w===void 0||A)A&&d.push(await l.forceFragmentFinalization()),u.push({timestamp:T.timestamp,independent:u.length===0||!t||T.type==="key"});else{let x=u[u.length-1];x.timestamp=Math.min(x.timestamp,T.timestamp)}k?(b(s&&f),await s.add(this.toMediaPacket(T),f),g++):(b(o&&p),await o.add(this.toMediaPacket(T),p),h++),m=Math.max(m,T.timestamp+T.duration)}return m}initTargetFor(t){return async()=>{b(this.output._target instanceof Je);let n=this.output._target;if(t.initSegment)return new Pa;if(t.singleFile){t.initSegment={path:t.singleFile.path,duration:0,timestamp:0,byteSize:0,byteOffset:0,info:null,parts:null};let i=t.singleFile.target.slice(t.singleFile.nextOffset);return i.on("write",({end:a})=>{t.initSegment.byteSize=Math.max(t.initSegment.byteSize,a)}),i.on("finalized",()=>{t.singleFile.nextOffset=t.initSegment.byteSize}),i}else{let i=uu(t),a=await this.getInitPath(i);uR(a),t.initSegment={path:a,duration:0,timestamp:0,byteSize:0,byteOffset:null,info:null,parts:null};let s=Ie(Ie(n.rootPath,t.path),a),o=await this.output._getTarget({path:s,isRoot:!1,mimeType:t.segmentFormat.mimeType});return o.on("write",({end:l})=>{t.initSegment.byteSize=Math.max(t.initSegment.byteSize,l)}),o.on("finalized",()=>{t.pendingInit=Promise.resolve(this.options.onInit?.(o,i))}),o}}}async drainPendingInit(t){let n=t.pendingInit;n&&(t.pendingInit=null,await n)}async evictLiveSegments(t){if(this.isLive){for(;t.writtenSegments.length>this.maxLiveSegmentCount;){let n=t.writtenSegments.shift();t.windowDuration-=n.duration,t.mediaSequence++,this.singleFilePerPlaylist||(b(n.info),await this.options.onSegmentPopped?.(n.path,n.info))}await this.broadcast("onSegmentAppended",t)}}async advanceSubtitlePlaylist(t){let n=t.subtitleBoundaries;if(b(n),t.done)return;let i=this.trackDatas.find(o=>o.track===t.tracks[0]);b(i);let a=i.info.cues;for(;n.length>0;){let o=n[0],l=o.timestamp+o.duration;if(!i.closed&&!a.some(c=>c.timestamp>=l)){let c=ne(n);if(c.timestamp+c.duration-l<=this.maxInterleaveDelta)return}n.shift(),await this.writeSubtitleSegment(t,i,o.timestamp,o.duration)}let s=this.subtitleBoundarySource!==null&&!this.subtitleBoundarySource.done;if(!(!i.closed||s)){if(a.length>0){let o=t.currentSegmentStartTimestamp??a[0].timestamp,l=a.reduce((c,u)=>Math.max(c,u.timestamp+u.duration),o);await this.writeSubtitleSegment(t,i,o,l-o)}await this.onPlaylistDone(t)}}async openSubtitleSingleFile(t,n){b(this.output._target instanceof Je);let i=this.output._target,a={n:t.nextSegmentId,format:t.segmentFormat,isSingleFile:!0,playlist:uu(t),parts:null,isLast:!0},s=await this.getSegmentPath(a);Nf(s);let o=await this.output._getTarget({path:Ie(Ie(i.rootPath,t.path),s),isRoot:!1,mimeType:t.segmentFormat.mimeType}),l=null;t.segmentFormat._isFragmentedIsobmff()?(l=$k(t.segmentFormat,o),l.subtitleSource=new fi(n.track.source._codec),l.output.addSubtitleTrack(l.subtitleSource,n.track.metadata),await this.startInnerOutput(l.output)):o._start(),t.singleFile={target:o,path:s,nextOffset:0,info:a,fragmentedIsobmffOutput:l}}async writeSubtitleSegment(t,n,i,a){b(this.output._target instanceof Je);let s=this.output._target,o=i+a,l=t.nextSegmentId===1?-1/0:i,c=n.info.cues.filter(S=>mh(S,l,o));this.singleFilePerPlaylist&&!t.singleFile&&await this.openSubtitleSingleFile(t,n);let u=null,d;t.singleFile?d=t.singleFile.path:(u={n:t.nextSegmentId,format:t.segmentFormat,isSingleFile:!1,playlist:uu(t),parts:null,isLast:!1},d=await this.getSegmentPath(u),Nf(d));let m=Ie(Ie(s.rootPath,t.path),d);t.nextSegmentId++;let f=0,p=null,g=t.singleFile?.fragmentedIsobmffOutput??null,h=g?.output??new pr({format:t.segmentFormat,target:new Je(m,async S=>{if(S.isRoot&&t.singleFile){let T=t.singleFile.target.slice(t.singleFile.nextOffset);return T.on("write",({end:w})=>f=Math.max(f,w)),T}let k=await this.output._getTarget({...S,isRoot:!1});return S.isRoot&&(p=k,k.on("write",({end:T})=>f=Math.max(f,T))),k}),initTarget:this.initTargetFor(t)}),y;if(g?(b(g.subtitleSource),y=g.subtitleSource):(y=new fi(n.track.source._codec),h.addSubtitleTrack(y,n.track.metadata)),t.segmentFormat instanceof du){let S=h._muxer;S.segmentStartTimestamp=i,S.preamble=n.info.config?.description??null}else h._muxer.subtitleSegmentWindow={start:i,duration:a};try{g||await this.startInnerOutput(h);for(let S of c)await y.add(S);g?f=await Xk(t):await h.finalize()}catch(S){throw await h.cancel(),S}u&&(b(p),u.isLast=n.closed&&(t.subtitleBoundaries?.length??0)===0,await this.drainPendingInit(t),await this.options.onSegment?.(p,u)),n.info.cues=n.info.cues.filter(S=>mh(S,o,1/0)),t.windowDuration+=a,t.writtenSegments.push({path:d,duration:a,timestamp:i,byteSize:f,byteOffset:t.singleFile?t.singleFile.nextOffset:null,info:u,parts:null}),t.singleFile&&(t.singleFile.nextOffset+=f),this.globalTargetDuration=Math.max(this.globalTargetDuration,a),t.currentSegmentStartTimestamp=o,await this.evictLiveSegments(t)}toMediaPacket(t){return this.mediaIsAddressedByItsOwnTimestamps?t:t.clone({timestamp:this.toMediaTimestamp(t.timestamp)})}toMediaTimestamp(t){return b(this.firstPacketTimestamp!==null),t-this.firstPacketTimestamp+this.mediaTimestampBase}async onPlaylistDone(t){if(b(!t.done),t.done=!0,t.singleFile){if(t.singleFile.fragmentedIsobmffOutput){await t.singleFile.fragmentedIsobmffOutput.output.finalize();let n=t.singleFile.fragmentedIsobmffOutput.output._muxer;t.indexRange=n.sidxByteRange}else await t.singleFile.target._flush(),await t.singleFile.target._finalize();await this.drainPendingInit(t),await this.options.onSegment?.(t.singleFile.target,t.singleFile.info)}await this.broadcast("onPlaylistDone",t)}async finalize(){(await Promise.all(this.playlists.map(n=>n.mutex.acquire()))).forEach(n=>n());for(let n of this.trackDatas)n.closed=!0;await Promise.all(this.playlists.map(n=>n.done||n.subtitleBoundaries?Promise.resolve():this.advancePlaylist(n))),await Promise.all(this.subtitlePlaylists.map(n=>n.done?Promise.resolve():this.advanceSubtitlePlaylist(n))),await this.broadcast("onFinalize")}},cR=r=>{if(typeof r!="string")throw new TypeError("options.getPlaylistPath must return or resolve to a string");if(/[\n\r"]/.test(r))throw new TypeError("Playlist paths cannot contain line feed, carriage return, or double quote characters.")},Nf=r=>{if(typeof r!="string")throw new TypeError("options.getSegmentPath must return or resolve to a string");if(/[\n\r"]/.test(r))throw new TypeError("Segment paths cannot contain line feed or carriage return characters.")},uR=r=>{if(typeof r!="string")throw new TypeError("options.getInitPath must return or resolve to a string");if(/[\n\r"]/.test(r))throw new TypeError("Init paths cannot contain line feed, carriage return, or double quote characters.")},dR=r=>r.every(e=>e.closed&&e.packets.length===0),uu=r=>({n:r.id,tracks:r.tracks,segmentFormat:r.segmentFormat});var lb="text/vtt",Qk=".vtt",mR="WEBVTT",fR=r=>{let e=r.preamble??mR,t=e.indexOf(`
|
|
69
|
+
`,n=!0),t+=this.variantTag(o)):t+=this.renditionTag(o,a);this.options.onMaster?.(t);let s=await this.host.acquireMutex();try{let o;if(this.host.numWrittenMasterPlaylists===0)o=await this.host.output._getRootWriter(!0);else{let l=await this.host.output._getTarget({path:e.rootPath,isRoot:!0,mimeType:cr});o=new Br(l,!0),o.start()}o.write(re.encode(t)),await o.flush(),await o.finalize(),this.host.noteMasterPlaylistWritten()}finally{s()}}async tryWriteMasterPlaylist(){b(this.host.isLive);for(let e of this.host.playlists)if(e.writtenSegments.length===0&&!e.done)return;await this.writeMasterPlaylist()}};var oR="subtitles",qk=r=>({...r.track.metadata,closedCaptions:void 0,decoderConfig:r.info.decoderConfig,primingPacket:r.info.primingPacket??void 0}),Gk=r=>({...r.track.metadata,decoderConfig:r.info.decoderConfig,primingPacket:r.info.primingPacket??void 0}),$k=(r,e)=>{let t={output:new pr({format:r,target:e}),videoSource:null,audioSource:null,subtitleSource:null,firstMoofPosition:null,currentFileSize:0};e.on("write",({end:a})=>{t.currentFileSize=Math.max(t.currentFileSize,a)});let n=t.output._muxer;n.minimumFragmentDuration=1/0;let i=n.formatOptions.onMoof;return n.formatOptions.onMoof=(a,s,o)=>{t.firstMoofPosition=s,i?.(a,s,o),n.formatOptions.onMoof=i},t},Xk=async r=>{let e=r.singleFile;return b(e?.fragmentedIsobmffOutput),await e.fragmentedIsobmffOutput.output._muxer.forceFragmentFinalization(),e.fragmentedIsobmffOutput.firstMoofPosition!==null&&!r.initSegment&&(r.initSegment={path:e.path,duration:0,timestamp:0,byteSize:e.fragmentedIsobmffOutput.firstMoofPosition,byteOffset:0,info:null,parts:null},e.nextOffset=e.fragmentedIsobmffOutput.firstMoofPosition),e.fragmentedIsobmffOutput.currentFileSize-e.nextOffset},lR=({metadata:r})=>[r.languageCode??ye,r.name??"",r.disposition?.default??!0,r.disposition?.primary??!1,r.disposition?.forced??!1].join("-"),el=class extends Ke{constructor(t,n,i){if(!(t._target instanceof Je))throw new TypeError("HLS outputs require `OutputOptions.target` to be a PathedTarget.");super(t);this.trackDatas=[];this.firstPacketTimestamp=null;this.isRelativeToUnixEpoch=!1;this.numWrittenMasterPlaylists=0;this.playlists=[];this.playlistDeclarations=[];this.subtitlePlaylists=[];this.subtitleBoundarySource=null;this.options=n,this.targetSegmentDuration=n.targetDuration??2,this.singleFilePerPlaylist=n.singleFilePerPlaylist??!1,this.separateRenditions=n.separateRenditions??!1,this.isLive=n.live??!1,this.maxLiveSegmentCount=n.maxLiveSegmentCount??1/0,this.partDuration=n.partDuration??null,this.mediaTimestampBase=n.mediaTimestampBase??10,this.globalTargetDuration=this.targetSegmentDuration,this.getPlaylistPath=n.getPlaylistPath??(({n:a})=>`playlist-${a}.m3u8`),this.getSegmentPath=n.getSegmentPath??(a=>a.isSingleFile?`segments-${a.playlist.n}${a.format.fileExtension}`:`segment-${a.playlist.n}-${a.n}${a.format.fileExtension}`),this.getInitPath=n.getInitPath??(a=>`init-${a.n}${a.segmentFormat.fileExtension}`),this.manifestEmitters=i(this),this.mediaIsAddressedByItsOwnTimestamps=this.manifestEmitters.some(a=>a.addressesMediaByItsOwnTimestamps)}startInnerOutput(t,n){let i=this.output._metadataTags;return t.setMetadataTags({...i,...n,...i.raw||n?.raw?{raw:{...i.raw,...n?.raw}}:{}}),t.start()}async broadcast(t,...n){for(let i of this.manifestEmitters){let a=i[t];a&&await a.apply(i,n)}}noteMasterPlaylistWritten(){this.numWrittenMasterPlaylists++}acquireMutex(){return this.mutex.acquire()}async start(){let t=await this.mutex.acquire(),n=this.output.tracks.some(m=>m.metadata.isRelativeToUnixEpoch),i=this.output.tracks.some(m=>!m.metadata.isRelativeToUnixEpoch);if(n&&i)throw new Error("All tracks must agree on `relativeToUnixEpoch`: some tracks are relative to the Unix epoch and some are not.");this.isRelativeToUnixEpoch=n;let{groups:a,groupAssignment:s,hasVideo:o}=this.buildRenditionGroups(),{variantStreams:l,unpairedVideoTracks:c,unpairedAudioTracks:u}=this.buildVariantStreams(a,s,o?"video":"audio");this.placeUnpairedTracks("video",c,a,l),this.placeUnpairedTracks("audio",u,a,l),await this.declareGroupRenditions(a);let d=await this.declareSubtitleRenditions();await this.declareVariants(l,d),d.length>0&&(this.subtitleBoundarySource=this.resolveSubtitleBoundarySource()),this.registerDeclaredTracks(),await this.broadcast("onStart"),t()}buildRenditionGroups(){let t=new Map,n=[],i=!1,a=!1,s=!1;for(let o of this.output.tracks){if(o.type==="video"&&(i=!0),o.isSubtitleTrack())continue;let l=new Map;for(let c of this.output.tracks){if(o===c||c.isSubtitleTrack()||!o.canBePairedWith(c))continue;if(o.type===c.type){a||(N._warn(`Illegal pairing of two ${o.type} tracks detected, which is not possible in HLS; treating them as unpaired.`),a=!0);continue}if(o.isVideoTrack()&&o.metadata.hasOnlyKeyPackets||c.isVideoTrack()&&c.metadata.hasOnlyKeyPackets){s||(N._warn("A key-packets-only video track is pairable with another track, which is not possible in HLS; treating them as unpaired."),s=!0);continue}let u=l.get(c.source._codec);u||l.set(c.source._codec,u=[]),u.push(c)}for(let[,c]of l){let u=c.map(f=>f.id).join("-");n.find(f=>f.key===u)||n.push({name:c[0].type+"-"+(n.length+1),key:u,tracks:c,needsEmit:!1,firstNoUri:!1});let m=t.get(o);m||t.set(o,m=[]),m.push(u)}}return{groups:n,groupAssignment:t,hasVideo:i}}buildVariantStreams(t,n,i){let a=[],s=[],o=[];for(let l of this.output.tracks){let c=n.get(l);if(!c){l.type==="video"?s.push(l):l.type==="audio"&&o.push(l);continue}if(b(c.length>0),l.type===i)for(let u of c){let d=t.find(m=>m.key===u);if(b(d),!this.separateRenditions&&c.length===1&&d.tracks.length===1){let m=n.get(d.tracks[0]);if(b(m!==void 0),m.length===1){let f=t.find(p=>p.key===m[0]);if(f.tracks.length===1){b(f.tracks[0]===l),a.push({tracks:[l,d.tracks[0]],linkedGroup:null});continue}}}a.push({tracks:[l],linkedGroup:d}),d.needsEmit=!0}}return{variantStreams:a,unpairedVideoTracks:s,unpairedAudioTracks:o}}placeUnpairedTracks(t,n,i,a){if(n.length===0)return;if(new Set(n.map(lR)).size===1){for(let o of n)a.push({tracks:[o],linkedGroup:null});return}let s={key:n.map(o=>o.id).join("-"),name:t+"-"+(i.length+1),tracks:n,needsEmit:!0,firstNoUri:!0};i.push(s),a.push({tracks:[n[0]],linkedGroup:s})}deduceSegmentFormat(t){let n=[],i=0,a=0,s=0,o=!1,l=null,c=-1/0;for(let u of t)u.isVideoTrack()?(i++,o||=(u.metadata.rotation??0)!==0||!!u.metadata.flip||!!u.metadata.transformationMatrix):u.isAudioTrack()?a++:s++,n.push(u.source._codec);for(let u of[Kk,...ot(this.options.segmentFormat)]){let d=u.getSupportedCodecs(),m=u.getSupportedTrackCounts();if(n.some(p=>!d.includes(p))||i<m.video.min||i>m.video.max||a<m.audio.min||a>m.audio.max||s<m.subtitle.min||s>m.subtitle.max)continue;let f=0;o&&u.supportsVideoTransformationMetadata&&f++,f>c&&(l=u,c=f)}return b(l),l}async registerPlaylist(t){let n=t[0].isSubtitleTrack();if(t.some(l=>this.playlists.some(c=>c.tracks.includes(l))))throw new Error("Internal error: track is already registered in a playlist.");let i=this.deduceSegmentFormat(t);i instanceof ws&&i._options.timestampOffset===void 0&&(i=new ws({...i._options,timestampOffset:0}));let a=this.playlists.length+1,s=await this.getPlaylistPath({n:a,tracks:t,segmentFormat:i});cR(s);let o={id:a,path:s,tracks:t,segmentFormat:i,currentSegmentStartTimestamp:null,currentSegmentStartTimestampIsFixed:!1,segmentGridOrigin:null,nextSegmentId:1,initSegment:null,pendingInit:null,indexRange:null,writtenSegments:[],windowDuration:0,peakBitrate:null,averageBitrate:null,mediaSequence:0,done:!1,subtitleBoundaries:n?[]:null,singleFile:null,mutex:new vt,bitrateCache:null};return this.playlists.push(o),n&&this.subtitlePlaylists.push(o),o}async declareGroupRenditions(t){for(let n of t)if(n.needsEmit)for(let i=0;i<n.tracks.length;i++){let a=n.tracks[i],s=this.playlists.find(o=>o.tracks[0].id===a.id);s??=await this.registerPlaylist([a]),this.playlistDeclarations.push({playlist:s,groupId:n.name,noUri:n.firstNoUri&&i===0,references:[]})}}async declareSubtitleRenditions(){let t=[];for(let n of this.output.tracks.filter(i=>i.isSubtitleTrack())){let i={playlist:await this.registerPlaylist([n]),groupId:oR,noUri:!1,references:[]};t.push(i),this.playlistDeclarations.push(i)}return t}async declareVariants(t,n){for(let i of t){let a=this.playlists.find(s=>s.tracks[0].id===i.tracks[0].id);a??=await this.registerPlaylist(i.tracks),this.playlistDeclarations.push({playlist:a,groupId:null,noUri:!1,references:[...i.linkedGroup?this.playlistDeclarations.filter(s=>s.groupId===i.linkedGroup.name):[],...n]})}}resolveSubtitleBoundarySource(){let t=this.playlists.filter(i=>i.subtitleBoundaries===null),n=t.find(i=>i.tracks.some(a=>a.isVideoTrack()))??t[0];if(!n)throw new Error("Subtitle tracks require at least one video or audio track, as subtitle segments are cut on the media segment boundaries. Add a video or audio track.");return n}registerDeclaredTracks(){for(let t of this.output.tracks)t.isVideoTrack()&&t.metadata.decoderConfig?this.getVideoTrackData(t,t.metadata.primingPacket??null,{decoderConfig:t.metadata.decoderConfig}):t.isAudioTrack()&&t.metadata.decoderConfig?this.getAudioTrackData(t,t.metadata.primingPacket??null,{decoderConfig:t.metadata.decoderConfig}):t.isSubtitleTrack()&&this.getSubtitleTrackData(t)}async getMimeType(){return cr}allTracksAreKnown(t){for(let n of t.tracks)if(!n.source._closed&&!this.trackDatas.some(i=>i.track===n))return!1;return!0}async onTrackClose(t){let n=this.trackDatas.find(s=>s.track===t);n&&(n.closed=!0);let i=this.playlists.find(s=>s.tracks.includes(t));b(i);let a=await i.mutex.acquire();try{i.subtitleBoundaries?await this.advanceSubtitlePlaylist(i):await this.advancePlaylist(i)}finally{a()}}getVideoTrackData(t,n,i){let a=this.trackDatas.find(o=>o.track===t);if(a)return a;Vn(i,t.source._codec),b(i),b(i?.decoderConfig);let s=this.playlists.filter(o=>o.tracks.includes(t));return b(s.length===1),a={track:t,packets:[],playlist:s[0],closed:!1,info:{type:"video",decoderConfig:i.decoderConfig,inBandParameterSets:!i.decoderConfig.description||t.metadata.parameterSets==="inBand",primingPacket:n}},this.trackDatas.push(a),a}getAudioTrackData(t,n,i){let a=this.trackDatas.find(o=>o.track===t);if(a)return a;tt(i,t.source._codec),b(i),b(i?.decoderConfig);let s=this.playlists.filter(o=>o.tracks.includes(t));return b(s.length===1),a={track:t,packets:[],playlist:s[0],closed:!1,info:{type:"audio",decoderConfig:i.decoderConfig,primingPacket:n}},this.trackDatas.push(a),a}async addEncodedVideoPacket(t,n,i){let a=this.getVideoTrackData(t,n,i),s=a.playlist,o=await s.mutex.acquire();try{this.validateTimestamp(t,n.timestamp,n.type==="key"),a.packets.push(n),this.firstPacketTimestamp??=n.timestamp,s.currentSegmentStartTimestamp===null?s.currentSegmentStartTimestamp=n.timestamp:s.currentSegmentStartTimestampIsFixed||(s.currentSegmentStartTimestamp=Math.min(s.currentSegmentStartTimestamp,n.timestamp)),await this.advancePlaylist(s)}finally{o()}}async addEncodedAudioPacket(t,n,i){let a=this.getAudioTrackData(t,n,i),s=a.playlist,o=await s.mutex.acquire();try{this.validateTimestamp(t,n.timestamp,n.type==="key"),a.packets.push(n),this.firstPacketTimestamp??=n.timestamp,s.currentSegmentStartTimestamp===null?s.currentSegmentStartTimestamp=n.timestamp:s.currentSegmentStartTimestampIsFixed||(s.currentSegmentStartTimestamp=Math.min(s.currentSegmentStartTimestamp,n.timestamp)),await this.advancePlaylist(s)}finally{o()}}getSubtitleTrackData(t,n){let i=this.trackDatas.find(s=>s.track===t);if(i)return i.info.config??=n?.config??null,i;let a=this.playlists.filter(s=>s.tracks.includes(t));return b(a.length===1),i={track:t,packets:[],playlist:a[0],closed:!1,info:{type:"subtitle",cues:[],config:n?.config??null}},this.trackDatas.push(i),i}async addSubtitleCue(t,n,i){let a=this.getSubtitleTrackData(t,i),s=a.playlist,o=await s.mutex.acquire();try{this.validateTimestamp(t,n.timestamp,!0),a.info.cues.push(n),await this.advanceSubtitlePlaylist(s)}finally{o()}}get maxInterleaveDelta(){return this.options.maxInterleaveDelta??wr}async advancePlaylist(t){if(b(!t.done),!this.allTracksAreKnown(t))return;let n=this.trackDatas.filter(o=>t.tracks.includes(o.track));if(t.currentSegmentStartTimestamp===null){n.every(o=>o.closed)&&await this.onPlaylistDone(t);return}let i=n.find(o=>o.info.type==="video"),a=n.find(o=>o.info.type==="audio"),s=()=>!a||!i||i.packets.length===0?!1:this.quietTrackMayBeSkipped(n,o=>o.packets,o=>o.timestamp);for(;;){let o=this.chooseSegmentCut(t,i,a,s);if(o===null)return;if(o.videoEndIndex===0&&o.audioEndIndex===0){n.every(m=>m.closed)&&await this.onPlaylistDone(t);return}let{segmentInfo:l,relativeSegmentPath:c,fullSegmentPath:u}=await this.openSegmentTarget(t,i,a),d=await this.writeSegmentMedia(t,i,a,o,u);await this.recordSegment(t,n,i,a,{...o,...d,segmentInfo:l,relativeSegmentPath:c}),await this.evictLiveSegments(t)}}chooseSegmentCut(t,n,i,a){b(t.currentSegmentStartTimestamp!==null);let s=this.options.nextSegmentBoundary?.(t.currentSegmentStartTimestamp)??null,o=s??t.currentSegmentStartTimestamp+this.targetSegmentDuration;(t.segmentGridOrigin===null||t.nextSegmentId===1)&&(t.segmentGridOrigin=t.currentSegmentStartTimestamp);let l=t.segmentGridOrigin,c=Math.round((t.currentSegmentStartTimestamp-l)/this.targetSegmentDuration),u=s??l+(c+1)*this.targetSegmentDuration,d=0,m=0;if(n&&(!n.closed||n.packets.length>0)){let f=n.packets.every(h=>h.timestamp<o),p=null,g=null;if(f){if(!n.closed)return null}else for(let h=0;h<n.packets.length;h++){let y=n.packets[h];if(p!==null&&y.timestamp>o)break;h>0&&y.type==="key"&&(p=y,g=h)}if(g!==null){if(d=g,i){let h=i.packets.findIndex(y=>y.timestamp>=p.timestamp);if(h!==-1)m=h;else if(i.closed||a())m=i.packets.length;else return null}}else{if(!n.closed)return null;d=n.packets.length;let h=ky(n.packets,S=>S.timestamp),y=n.packets[h];if(b(y),i)if(y.timestamp<o){let S=i.packets.findIndex(k=>k.timestamp>=o);if(S!==-1)m=S;else if(i.closed||a())m=i.packets.length;else return null}else{let S=i.packets.findIndex(k=>k.timestamp>y.timestamp);if(S!==-1)m=S;else if(i.closed||a())m=i.packets.length;else return null}}}else if(i&&(!i.closed||i.packets.length>0))if(i.packets.every(p=>p.timestamp<u))if(i.closed)m=i.packets.length;else return null;else{let p=i.packets.findIndex(y=>y.timestamp>=u);b(p!==-1);let g=i.packets[p-1],h=s===null&&g!==void 0&&u-g.timestamp<=i.packets[p].timestamp-u?p-1:p;m=Math.max(h,1)}return{videoEndIndex:d,audioEndIndex:m}}async openSegmentTarget(t,n,i){let a=null,s,o;b(this.output._target instanceof Je);let l=this.output._target;if(this.singleFilePerPlaylist)if(t.singleFile===null){let c={n:t.nextSegmentId,format:t.segmentFormat,isSingleFile:!0,playlist:uu(t),parts:null,isLast:!0};s=await this.getSegmentPath(c),Nf(s),o=Ie(Ie(l.rootPath,t.path),s);let u=await this.output._getTarget({path:o,isRoot:!1,mimeType:t.segmentFormat.mimeType}),d=null;t.segmentFormat._isFragmentedIsobmff()?(d=$k(t.segmentFormat,u),n&&(d.videoSource=new ui(n.track.source._codec),d.output.addVideoTrack(d.videoSource,qk(n))),i&&(d.audioSource=new mi(i.track.source._codec),d.output.addAudioTrack(d.audioSource,Gk(i))),await this.startInnerOutput(d.output)):u._start(),t.singleFile={target:u,path:s,nextOffset:0,info:c,fragmentedIsobmffOutput:d}}else s=t.singleFile.path,o=Ie(Ie(l.rootPath,t.path),s);else a={n:t.nextSegmentId,format:t.segmentFormat,isSingleFile:!1,playlist:uu(t),parts:null,isLast:!1},s=await this.getSegmentPath(a),Nf(s),o=Ie(Ie(l.rootPath,t.path),s),t.nextSegmentId++;return{segmentInfo:a,relativeSegmentPath:s,fullSegmentPath:o}}async writeSegmentMedia(t,n,i,{videoEndIndex:a,audioEndIndex:s},o){let l=0,c=null,u=-1/0,d=[],m=[],f=null,p=null,g=null,h;try{if(t.singleFile?.fragmentedIsobmffOutput)f=t.singleFile.fragmentedIsobmffOutput.output,p=t.singleFile.fragmentedIsobmffOutput.videoSource,g=t.singleFile.fragmentedIsobmffOutput.audioSource;else{if(f=new pr({format:t.segmentFormat,target:new Je(o,async k=>{let T={...k,isRoot:!1};if(k.isRoot)if(t.singleFile){let w=t.singleFile.target.slice(t.singleFile.nextOffset);return w.on("write",({end:A})=>l=Math.max(l,A)),w}else{let w=await this.output._getTarget(T);return c=w,w.on("write",({end:A})=>l=Math.max(l,A)),w}return this.output._getTarget(T)}),initTarget:this.initTargetFor(t)}),n&&(p=new ui(n.track.source._codec),f.addVideoTrack(p,qk(n))),i&&(g=new mi(i.track.source._codec),f.addAudioTrack(g,Gk(i)),!t.segmentFormat.supportsTimestampedMediaData&&s>0)){let k=this.toMediaTimestamp(i.packets[0].timestamp),T=Ya(k),w=new Uint8Array(Er.length+1+8);w.set(re.encode(Er),0);let A=z(w);A.setUint32(Er.length+1,Math.floor(T/2**32)),A.setUint32(Er.length+5,T%2**32),h={raw:{PRIV:w}}}await this.startInnerOutput(f,h)}let y=f._muxer,S=y instanceof ps&&y.isFragmented?this.options.partDuration:void 0;u=S===void 0?await this.addSegmentPackets(n,i,{videoEndIndex:a,audioEndIndex:s},p,g):await this.addSegmentPacketsInParts(n,i,{videoEndIndex:a,audioEndIndex:s},p,g,y,S,d,m),t.singleFile?.fragmentedIsobmffOutput?l=await Xk(t):await f.finalize()}catch(y){throw await f?.cancel(),y}return{segmentSize:l,maxEndTimestamp:u,partStarts:d,partEnds:m,outputTarget:c}}async recordSegment(t,n,i,a,{videoEndIndex:s,audioEndIndex:o,segmentInfo:l,relativeSegmentPath:c,segmentSize:u,maxEndTimestamp:d,partStarts:m,partEnds:f,outputTarget:p}){b(t.currentSegmentStartTimestamp!==null),s>0&&(b(i),i.packets.splice(0,s)),o>0&&(b(a),a.packets.splice(0,o));let g=1/0;i&&i.packets.length>0&&(g=i.packets[0].timestamp),a&&a.packets.length>0&&(g=Math.min(g,a.packets[0].timestamp));let h=g<1/0?g:d;b(Number.isFinite(h));let y=h-t.currentSegmentStartTimestamp;b(y>=0);let S=null;if(m.length>0){let k=t.singleFile?.fragmentedIsobmffOutput?t.singleFile.nextOffset:0,T=[0,...f.map(A=>A-k),u],w=t.currentSegmentStartTimestamp;S=m.map((A,x)=>({offset:T[x],size:T[x+1]-T[x],duration:(m[x+1]?.timestamp??h)-(x===0?w:A.timestamp),independent:A.independent}))}if(l&&(b(p),l.parts=S,l.isLast=dR(n),await this.drainPendingInit(t),await this.options.onSegment?.(p,l)),t.windowDuration+=y,t.writtenSegments.push({path:c,duration:y,timestamp:t.currentSegmentStartTimestamp,byteSize:u,byteOffset:t.singleFile?t.singleFile.nextOffset:null,info:l??null,parts:S}),this.globalTargetDuration=Math.max(this.globalTargetDuration,y),t===this.subtitleBoundarySource){let k={timestamp:t.currentSegmentStartTimestamp,duration:y};for(let T of this.subtitlePlaylists){T.subtitleBoundaries.push(k);let w=await T.mutex.acquire();try{await this.advanceSubtitlePlaylist(T)}finally{w()}}}t.currentSegmentStartTimestamp=h,t.currentSegmentStartTimestampIsFixed=!0,t.singleFile&&(t.singleFile.nextOffset+=u)}async addSegmentPackets(t,n,{videoEndIndex:i,audioEndIndex:a},s,o){let l=-1/0;if(t){b(s);let c={decoderConfig:t.info.decoderConfig};for(let u=0;u<i;u++){let d=t.packets[u];await s.add(this.toMediaPacket(d),c),l=Math.max(l,d.timestamp+d.duration)}}if(n){b(o);let c={decoderConfig:n.info.decoderConfig};for(let u=0;u<a;u++){let d=n.packets[u];await o.add(this.toMediaPacket(d),c),l=Math.max(l,d.timestamp+d.duration)}}return l}async addSegmentPacketsInParts(t,n,{videoEndIndex:i,audioEndIndex:a},s,o,l,c,u,d){let m=-1/0;b(l instanceof ps);let f=t&&{decoderConfig:t.info.decoderConfig},p=n&&{decoderConfig:n.info.decoderConfig},g=0,h=0;for(;g<i||h<a;){let y=g<i?t.packets[g]:null,S=h<a?n.packets[h]:null,k=y!==null&&(S===null||y.timestamp<=S.timestamp),T=k?y:S,w=u.at(-1),A=w!==void 0&&(k||!t)&&T.timestamp+T.duration>w.timestamp+c+1e-6;if(w===void 0||A)A&&d.push(await l.forceFragmentFinalization()),u.push({timestamp:T.timestamp,independent:u.length===0||!t||T.type==="key"});else{let x=u[u.length-1];x.timestamp=Math.min(x.timestamp,T.timestamp)}k?(b(s&&f),await s.add(this.toMediaPacket(T),f),g++):(b(o&&p),await o.add(this.toMediaPacket(T),p),h++),m=Math.max(m,T.timestamp+T.duration)}return m}initTargetFor(t){return async()=>{b(this.output._target instanceof Je);let n=this.output._target;if(t.initSegment)return new Pa;if(t.singleFile){t.initSegment={path:t.singleFile.path,duration:0,timestamp:0,byteSize:0,byteOffset:0,info:null,parts:null};let i=t.singleFile.target.slice(t.singleFile.nextOffset);return i.on("write",({end:a})=>{t.initSegment.byteSize=Math.max(t.initSegment.byteSize,a)}),i.on("finalized",()=>{t.singleFile.nextOffset=t.initSegment.byteSize}),i}else{let i=uu(t),a=await this.getInitPath(i);uR(a),t.initSegment={path:a,duration:0,timestamp:0,byteSize:0,byteOffset:null,info:null,parts:null};let s=Ie(Ie(n.rootPath,t.path),a),o=await this.output._getTarget({path:s,isRoot:!1,mimeType:t.segmentFormat.mimeType});return o.on("write",({end:l})=>{t.initSegment.byteSize=Math.max(t.initSegment.byteSize,l)}),o.on("finalized",()=>{t.pendingInit=Promise.resolve(this.options.onInit?.(o,i))}),o}}}async drainPendingInit(t){let n=t.pendingInit;n&&(t.pendingInit=null,await n)}async evictLiveSegments(t){if(this.isLive){for(;t.writtenSegments.length>this.maxLiveSegmentCount;){let n=t.writtenSegments.shift();t.windowDuration-=n.duration,t.mediaSequence++,this.singleFilePerPlaylist||(b(n.info),await this.options.onSegmentPopped?.(n.path,n.info))}await this.broadcast("onSegmentAppended",t)}}async advanceSubtitlePlaylist(t){let n=t.subtitleBoundaries;if(b(n),t.done)return;let i=this.trackDatas.find(o=>o.track===t.tracks[0]);b(i);let a=i.info.cues;for(;n.length>0;){let o=n[0],l=o.timestamp+o.duration;if(!i.closed&&!a.some(c=>c.timestamp>=l)){let c=ne(n);if(c.timestamp+c.duration-l<=this.maxInterleaveDelta)return}n.shift(),await this.writeSubtitleSegment(t,i,o.timestamp,o.duration)}let s=this.subtitleBoundarySource!==null&&!this.subtitleBoundarySource.done;if(!(!i.closed||s)){if(a.length>0){let o=t.currentSegmentStartTimestamp??a[0].timestamp,l=a.reduce((c,u)=>Math.max(c,u.timestamp+u.duration),o);await this.writeSubtitleSegment(t,i,o,l-o)}await this.onPlaylistDone(t)}}async openSubtitleSingleFile(t,n){b(this.output._target instanceof Je);let i=this.output._target,a={n:t.nextSegmentId,format:t.segmentFormat,isSingleFile:!0,playlist:uu(t),parts:null,isLast:!0},s=await this.getSegmentPath(a);Nf(s);let o=await this.output._getTarget({path:Ie(Ie(i.rootPath,t.path),s),isRoot:!1,mimeType:t.segmentFormat.mimeType}),l=null;t.segmentFormat._isFragmentedIsobmff()?(l=$k(t.segmentFormat,o),l.subtitleSource=new fi(n.track.source._codec),l.output.addSubtitleTrack(l.subtitleSource,n.track.metadata),await this.startInnerOutput(l.output)):o._start(),t.singleFile={target:o,path:s,nextOffset:0,info:a,fragmentedIsobmffOutput:l}}async writeSubtitleSegment(t,n,i,a){b(this.output._target instanceof Je);let s=this.output._target,o=i+a,l=t.nextSegmentId===1?-1/0:i,c=n.info.cues.filter(S=>mh(S,l,o));this.singleFilePerPlaylist&&!t.singleFile&&await this.openSubtitleSingleFile(t,n);let u=null,d;t.singleFile?d=t.singleFile.path:(u={n:t.nextSegmentId,format:t.segmentFormat,isSingleFile:!1,playlist:uu(t),parts:null,isLast:!1},d=await this.getSegmentPath(u),Nf(d));let m=Ie(Ie(s.rootPath,t.path),d);t.nextSegmentId++;let f=0,p=null,g=t.singleFile?.fragmentedIsobmffOutput??null,h=g?.output??new pr({format:t.segmentFormat,target:new Je(m,async S=>{if(S.isRoot&&t.singleFile){let T=t.singleFile.target.slice(t.singleFile.nextOffset);return T.on("write",({end:w})=>f=Math.max(f,w)),T}let k=await this.output._getTarget({...S,isRoot:!1});return S.isRoot&&(p=k,k.on("write",({end:T})=>f=Math.max(f,T))),k}),initTarget:this.initTargetFor(t)}),y;if(g?(b(g.subtitleSource),y=g.subtitleSource):(y=new fi(n.track.source._codec),h.addSubtitleTrack(y,n.track.metadata)),t.segmentFormat instanceof du){let S=h._muxer;S.segmentStartTimestamp=i,S.preamble=n.info.config?.description??null}else h._muxer.subtitleSegmentWindow={start:i,duration:a};try{g||await this.startInnerOutput(h);for(let S of c)await y.add(S);g?f=await Xk(t):await h.finalize()}catch(S){throw await h.cancel(),S}u&&(b(p),u.isLast=n.closed&&(t.subtitleBoundaries?.length??0)===0,await this.drainPendingInit(t),await this.options.onSegment?.(p,u)),n.info.cues=n.info.cues.filter(S=>mh(S,o,1/0)),t.windowDuration+=a,t.writtenSegments.push({path:d,duration:a,timestamp:i,byteSize:f,byteOffset:t.singleFile?t.singleFile.nextOffset:null,info:u,parts:null}),t.singleFile&&(t.singleFile.nextOffset+=f),this.globalTargetDuration=Math.max(this.globalTargetDuration,a),t.currentSegmentStartTimestamp=o,await this.evictLiveSegments(t)}toMediaPacket(t){return this.mediaIsAddressedByItsOwnTimestamps?t:t.clone({timestamp:this.toMediaTimestamp(t.timestamp)})}toMediaTimestamp(t){return b(this.firstPacketTimestamp!==null),t-this.firstPacketTimestamp+this.mediaTimestampBase}async onPlaylistDone(t){if(b(!t.done),t.done=!0,t.singleFile){if(t.singleFile.fragmentedIsobmffOutput){await t.singleFile.fragmentedIsobmffOutput.output.finalize();let n=t.singleFile.fragmentedIsobmffOutput.output._muxer;t.indexRange=n.sidxByteRange}else await t.singleFile.target._flush(),await t.singleFile.target._finalize();await this.drainPendingInit(t),await this.options.onSegment?.(t.singleFile.target,t.singleFile.info)}await this.broadcast("onPlaylistDone",t)}async finalize(){(await Promise.all(this.playlists.map(n=>n.mutex.acquire()))).forEach(n=>n());for(let n of this.trackDatas)n.closed=!0;await Promise.all(this.playlists.map(n=>n.done||n.subtitleBoundaries?Promise.resolve():this.advancePlaylist(n))),await Promise.all(this.subtitlePlaylists.map(n=>n.done?Promise.resolve():this.advanceSubtitlePlaylist(n))),await this.broadcast("onFinalize")}},cR=r=>{if(typeof r!="string")throw new TypeError("options.getPlaylistPath must return or resolve to a string");if(/[\n\r"]/.test(r))throw new TypeError("Playlist paths cannot contain line feed, carriage return, or double quote characters.")},Nf=r=>{if(typeof r!="string")throw new TypeError("options.getSegmentPath must return or resolve to a string");if(/[\n\r"]/.test(r))throw new TypeError("Segment paths cannot contain line feed or carriage return characters.")},uR=r=>{if(typeof r!="string")throw new TypeError("options.getInitPath must return or resolve to a string");if(/[\n\r"]/.test(r))throw new TypeError("Init paths cannot contain line feed, carriage return, or double quote characters.")},dR=r=>r.every(e=>e.closed&&e.packets.length===0),uu=r=>({n:r.id,tracks:r.tracks,segmentFormat:r.segmentFormat});var lb="text/vtt",Qk=".vtt",mR="WEBVTT",fR=r=>{let e=r.preamble??mR,t=e.indexOf(`
|
|
70
70
|
`),n=t===-1?e:e.slice(0,t),i=t===-1?"":e.slice(t),a=`X-TIMESTAMP-MAP=LOCAL:${kn(Math.round(1e3*r.startTimestamp))},MPEGTS:${Math.round(r.startTimestamp*He)}`,s=`${n}
|
|
71
71
|
${a}${i}
|
|
72
72
|
`;for(let o of r.cues)s+=`
|
|
73
73
|
`,o.identifier&&(s+=`${o.identifier}
|
|
74
74
|
`),s+=kn(Math.round(1e3*o.timestamp))+" --> "+kn(Math.round(1e3*(o.timestamp+o.duration))),o.settings&&(s+=` ${o.settings}`),s+=`
|
|
75
75
|
${o.text}
|
|
76
|
-
`;return s},Lf=class extends Ke{constructor(){super(...arguments);this.cues=[];this.segmentStartTimestamp=0;this.preamble=null}async start(){this.writer=await this.output._getRootWriter(!0)}async getMimeType(){return lb}async addEncodedVideoPacket(){throw new E("WebVTT does not support video.")}async addEncodedAudioPacket(){throw new E("WebVTT does not support audio.")}async addSubtitleCue(t,n,i){let a=await this.mutex.acquire();try{this.preamble??=i?.config?.description??null,this.cues.push(n)}finally{a()}}async finalize(){let t=await this.mutex.acquire();try{this.writer.write(re.encode(fR({preamble:this.preamble,startTimestamp:this.segmentStartTimestamp,cues:this.cues}))),await this.writer.flush()}finally{t()}}};var nt=class{get supportsVideoRotationMetadata(){return this.supportsVideoTransformationMetadata}get requiresMaximumPacketCount(){return!1}getSupportedVideoCodecs(){return this.getSupportedCodecs().filter(e=>Te.includes(e))}getSupportedAudioCodecs(){return this.getSupportedCodecs().filter(e=>Ee.includes(e))}getSupportedSubtitleCodecs(){return this.getSupportedCodecs().filter(e=>Mt.includes(e))}_codecUnsupportedHint(e){return""}_trackTypeUnsupportedHint(e){return""}_isFragmentedIsobmff(){return!1}},hi=class extends nt{constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.fastStart!==void 0&&![!1,"in-memory","reserve","fragmented"].includes(e.fastStart))throw new TypeError("options.fastStart, when provided, must be false, 'in-memory', 'reserve', or 'fragmented'.");if(e.minimumFragmentDuration!==void 0&&(!Ve(e.minimumFragmentDuration)||e.minimumFragmentDuration<0))throw new TypeError("options.minimumFragmentDuration, when provided, must be a non-negative number.");if(e.segmentIndex!==void 0&&typeof e.segmentIndex!="boolean")throw new TypeError("options.segmentIndex, when provided, must be a boolean.");if(e.onFtyp!==void 0&&typeof e.onFtyp!="function")throw new TypeError("options.onFtyp, when provided, must be a function.");if(e.onMoov!==void 0&&typeof e.onMoov!="function")throw new TypeError("options.onMoov, when provided, must be a function.");if(e.onMdat!==void 0&&typeof e.onMdat!="function")throw new TypeError("options.onMdat, when provided, must be a function.");if(e.onMoof!==void 0&&typeof e.onMoof!="function")throw new TypeError("options.onMoof, when provided, must be a function.");if(e.metadataFormat!==void 0&&!["mdir","mdta","udta","auto"].includes(e.metadataFormat))throw new TypeError("options.metadataFormat, when provided, must be either 'auto', 'mdir', 'mdta', or 'udta'.");super(),this._options=e}getSupportedTrackCounts(){return{video:{min:0,max:4294967295},audio:{min:0,max:4294967295},subtitle:{min:0,max:4294967295},total:{min:0,max:4294967295}}}get supportsVideoTransformationMetadata(){return!0}get supportsTimestampedMediaData(){return!0}get negativeTimestampSupport(){return"full"}get requiresMaximumPacketCount(){return this._options.fastStart==="reserve"}_createMuxer(e){return new ps(e,this)}_isFragmentedIsobmff(){return this._options.fastStart==="fragmented"}},ks=class extends hi{constructor(e){super(e)}get _name(){return"MP4"}get fileExtension(){return".mp4"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...Te,...rn,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...Mt]}_codecUnsupportedHint(e){return new gi().getSupportedCodecs().includes(e)?" Switching to MOV will grant support for this codec.":""}},Ca=class extends hi{constructor(e){super(e)}get _name(){return"CMAF"}get fileExtension(){return".m4s"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...Te,...rn,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...Mt]}},gi=class extends hi{constructor(e){super(e)}get _name(){return"MOV"}get fileExtension(){return".mov"}get mimeType(){return"video/quicktime"}getSupportedCodecs(){return[...Te,...Ee]}_codecUnsupportedHint(e){return new ks().getSupportedCodecs().includes(e)?" Switching to MP4 will grant support for this codec.":""}},tl=class extends nt{constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.appendOnly!==void 0&&typeof e.appendOnly!="boolean")throw new TypeError("options.appendOnly, when provided, must be a boolean.");if(e.minimumClusterDuration!==void 0&&(!Ve(e.minimumClusterDuration)||e.minimumClusterDuration<0))throw new TypeError("options.minimumClusterDuration, when provided, must be a non-negative number.");if(e.onEbmlHeader!==void 0&&typeof e.onEbmlHeader!="function")throw new TypeError("options.onEbmlHeader, when provided, must be a function.");if(e.onSegmentHeader!==void 0&&typeof e.onSegmentHeader!="function")throw new TypeError("options.onHeader, when provided, must be a function.");if(e.onCluster!==void 0&&typeof e.onCluster!="function")throw new TypeError("options.onCluster, when provided, must be a function.");super(),this._options=e}_createMuxer(e){return new gf(e,this)}get _name(){return"Matroska"}getSupportedTrackCounts(){return{video:{min:0,max:127},audio:{min:0,max:127},subtitle:{min:0,max:127},total:{min:0,max:127}}}get fileExtension(){return".mkv"}get mimeType(){return"video/x-matroska"}getSupportedCodecs(){return[...Te,...rn,...Se.filter(e=>!["pcm-s8","pcm-f32be","pcm-f64be","ulaw","alaw"].includes(e)),"webvtt"]}get supportsVideoTransformationMetadata(){return!1}get supportsTimestampedMediaData(){return!0}get negativeTimestampSupport(){return"prefer-non-negative"}},Ia=class extends tl{constructor(e){super(e)}getSupportedCodecs(){return[...Te.filter(e=>["vp8","vp9","av1"].includes(e)),...Ee.filter(e=>["opus","vorbis"].includes(e)),"webvtt"]}get _name(){return"WebM"}get fileExtension(){return".webm"}get mimeType(){return"video/webm"}_codecUnsupportedHint(e){return new tl().getSupportedCodecs().includes(e)?" Switching to MKV will grant support for this codec.":""}},Vf=class extends nt{constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.xingHeader!==void 0&&typeof e.xingHeader!="boolean")throw new TypeError("options.xingHeader, when provided, must be a boolean.");if(e.onXingFrame!==void 0&&typeof e.onXingFrame!="function")throw new TypeError("options.onXingFrame, when provided, must be a function.");super(),this._options=e}_createMuxer(e){return new yf(e,this)}get _name(){return"MP3"}getSupportedTrackCounts(){return{video:{min:0,max:0},audio:{min:1,max:1},subtitle:{min:0,max:0},total:{min:1,max:1}}}get fileExtension(){return".mp3"}get mimeType(){return"audio/mpeg"}getSupportedCodecs(){return["mp3"]}get supportsVideoTransformationMetadata(){return!1}get supportsTimestampedMediaData(){return!1}get negativeTimestampSupport(){return null}},zf=class extends nt{constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.large!==void 0&&typeof e.large!="boolean")throw new TypeError("options.large, when provided, must be a boolean.");if(e.metadataFormat!==void 0&&!["info","id3"].includes(e.metadataFormat))throw new TypeError("options.metadataFormat, when provided, must be either 'info' or 'id3'.");if(e.onHeader!==void 0&&typeof e.onHeader!="function")throw new TypeError("options.onHeader, when provided, must be a function.");super(),this._options=e}_createMuxer(e){return new Af(e,this)}get _name(){return"WAVE"}getSupportedTrackCounts(){return{video:{min:0,max:0},audio:{min:1,max:1},subtitle:{min:0,max:0},total:{min:1,max:1}}}get fileExtension(){return".wav"}get mimeType(){return"audio/wav"}getSupportedCodecs(){return[...Se.filter(e=>["pcm-s16","pcm-s24","pcm-s32","pcm-f32","pcm-f64","pcm-u8","ulaw","alaw"].includes(e))]}get supportsVideoTransformationMetadata(){return!1}get supportsTimestampedMediaData(){return!1}get negativeTimestampSupport(){return null}},Hf=class extends nt{constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.maximumPageDuration!==void 0&&(!Ve(e.maximumPageDuration)||e.maximumPageDuration<=0))throw new TypeError("options.maximumPageDuration, when provided, must be a positive number.");if(e.maxInterleaveDelta!==void 0&&!(e.maxInterleaveDelta>0))throw new TypeError("options.maxInterleaveDelta, when provided, must be a positive number.");if(e.onPage!==void 0&&typeof e.onPage!="function")throw new TypeError("options.onPage, when provided, must be a function.");super(),this._options=e}_createMuxer(e){return new Sf(e,this)}get _name(){return"Ogg"}getSupportedTrackCounts(){return{video:{min:0,max:0},audio:{min:0,max:4294967296},subtitle:{min:0,max:0},total:{min:0,max:4294967296}}}get fileExtension(){return".ogg"}get mimeType(){return"application/ogg"}getSupportedCodecs(){return[...Ee.filter(e=>["vorbis","opus"].includes(e))]}get supportsVideoTransformationMetadata(){return!1}get supportsTimestampedMediaData(){return!0}get negativeTimestampSupport(){return"none"}},Wf=class extends nt{constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.onFrame!==void 0&&typeof e.onFrame!="function")throw new TypeError("options.onFrame, when provided, must be a function.");super(),this._options=e}_createMuxer(e){return new cf(e,this)}get _name(){return"ADTS"}getSupportedTrackCounts(){return{video:{min:0,max:0},audio:{min:1,max:1},subtitle:{min:0,max:0},total:{min:1,max:1}}}get fileExtension(){return".aac"}get mimeType(){return"audio/aac"}getSupportedCodecs(){return["aac"]}get supportsVideoTransformationMetadata(){return!1}get supportsTimestampedMediaData(){return!1}get negativeTimestampSupport(){return null}},qf=class extends nt{constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.appendOnly!==void 0&&typeof e.appendOnly!="boolean")throw new TypeError("options.appendOnly, when provided, must be a boolean.");super(),this._options=e}_createMuxer(e){return new uf(e,this)}get _name(){return"FLAC"}getSupportedTrackCounts(){return{video:{min:0,max:0},audio:{min:1,max:1},subtitle:{min:0,max:0},total:{min:1,max:1}}}get fileExtension(){return".flac"}get mimeType(){return"audio/flac"}getSupportedCodecs(){return["flac"]}get supportsVideoTransformationMetadata(){return!1}get supportsTimestampedMediaData(){return!1}get negativeTimestampSupport(){return null}},ws=class extends nt{constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.timestampOffset!==void 0&&(!Number.isFinite(e.timestampOffset)||e.timestampOffset<0))throw new TypeError("options.timestampOffset, when provided, must be a non-negative number.");if(e.scte35Pid!==void 0&&(!Number.isInteger(e.scte35Pid)||e.scte35Pid<16||e.scte35Pid>8190))throw new TypeError("options.scte35Pid, when provided, must be an integer between 0x0010 and 0x1ffe.");if(e.tableRepeatInterval!==void 0&&!(e.tableRepeatInterval>0))throw new TypeError("options.tableRepeatInterval, when provided, must be a positive number.");if(e.privateStreams!==void 0){if(!Array.isArray(e.privateStreams))throw new TypeError("options.privateStreams, when provided, must be an array.");let t=new Set;for(let n of e.privateStreams){if(!n||typeof n!="object")throw new TypeError("Each entry of options.privateStreams must be an object.");if(!Number.isInteger(n.pid)||n.pid<16||n.pid>8190)throw new TypeError("A private stream's pid must be an integer between 0x0010 and 0x1ffe.");if(n.pid===e.scte35Pid||t.has(n.pid))throw new TypeError(`Private stream PID ${n.pid} is declared more than once.`);if(t.add(n.pid),n.streamType!==void 0&&(!Number.isInteger(n.streamType)||n.streamType<0||n.streamType>255))throw new TypeError("A private stream's streamType, when provided, must be a byte.");if(!Array.isArray(n.descriptors))throw new TypeError("A private stream's descriptors must be an array of Uint8Array.");let i=0;for(let a of n.descriptors){if(!(a instanceof Uint8Array)||a.byteLength<2)throw new TypeError("Each private stream descriptor must be a Uint8Array of at least two bytes.");if(a[1]!==a.byteLength-2)throw new TypeError("A private stream descriptor's length byte must equal its size minus two.");i+=a.byteLength}if(i>4095)throw new TypeError("A private stream's descriptors must fit in a 12-bit ES_info_length.")}}if(e.maxInterleaveDelta!==void 0&&!(e.maxInterleaveDelta>0))throw new TypeError("options.maxInterleaveDelta, when provided, must be a positive number.");if(e.onPacket!==void 0&&typeof e.onPacket!="function")throw new TypeError("options.onPacket, when provided, must be a function.");if(e.sampleAesEncryption!==void 0){let{key:t,iv:n}=e.sampleAesEncryption;if(!(t instanceof Uint8Array)||t.byteLength!==16)throw new TypeError("options.sampleAesEncryption.key must be a 16-byte Uint8Array.");if(!(n instanceof Uint8Array)||n.byteLength!==16)throw new TypeError("options.sampleAesEncryption.iv must be a 16-byte Uint8Array.")}super(),this._options=e}_createMuxer(e){return new Ea(e,this)}get _name(){return"MPEG-TS"}getSupportedTrackCounts(){return{video:{min:0,max:16},audio:{min:0,max:32},subtitle:{min:0,max:0},total:{min:0,max:48}}}get fileExtension(){return".ts"}get mimeType(){return"video/MP2T"}getSupportedCodecs(){return[...Te.filter(e=>["avc","hevc","mpeg2"].includes(e)),...Ee.filter(e=>["aac","mp3","mp2","ac3","eac3","dts"].includes(e))]}get supportsVideoTransformationMetadata(){return!1}get supportsTimestampedMediaData(){return!0}get negativeTimestampSupport(){return"prefer-non-negative"}},du=class extends nt{_createMuxer(e){return new Lf(e)}get _name(){return"WebVTT"}get fileExtension(){return Qk}get mimeType(){return lb}getSupportedCodecs(){return["webvtt"]}getSupportedTrackCounts(){return{video:{min:0,max:0},audio:{min:0,max:0},subtitle:{min:1,max:1},total:{min:1,max:1}}}get supportsVideoTransformationMetadata(){return!1}get supportsTimestampedMediaData(){return!0}get negativeTimestampSupport(){return"none"}},Kk=new du,mu=class extends nt{constructor(e){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(!(e.segmentFormat instanceof nt)&&(!Array.isArray(e.segmentFormat)||e.segmentFormat.length===0||!e.segmentFormat.every(t=>t instanceof nt)))throw new TypeError("options.segmentFormat must be an OutputFormat or a non-empty array of OutputFormat instances.");if(e.targetDuration!==void 0&&(typeof e.targetDuration!="number"||e.targetDuration<=0))throw new TypeError("options.targetDuration, when provided, must be a positive number.");if(e.partDuration!==void 0&&(!Number.isFinite(e.partDuration)||e.partDuration<=0))throw new TypeError("options.partDuration, when provided, must be a positive finite number.");if(e.singleFilePerPlaylist!==void 0&&typeof e.singleFilePerPlaylist!="boolean")throw new TypeError("options.singleFilePerPlaylist, when provided, must be a boolean.");if(e.live!==void 0&&typeof e.live!="boolean")throw new TypeError("options.live, when provided, must be a boolean.");if(e.maxLiveSegmentCount!==void 0&&(typeof e.maxLiveSegmentCount!="number"||e.maxLiveSegmentCount<1||Number.isFinite(e.maxLiveSegmentCount)&&!Number.isInteger(e.maxLiveSegmentCount)))throw new TypeError("options.maxLiveSegmentCount, when provided, must be a positive integer or Infinity.");if(e.mediaTimestampBase!==void 0&&!Number.isFinite(e.mediaTimestampBase))throw new TypeError("options.mediaTimestampBase, when provided, must be a finite number.");if(e.getPlaylistPath!==void 0&&typeof e.getPlaylistPath!="function")throw new TypeError("options.getPlaylistPath, when provided, must be a function.");if(e.getSegmentPath!==void 0&&typeof e.getSegmentPath!="function")throw new TypeError("options.getSegmentPath, when provided, must be a function.");if(e.getInitPath!==void 0&&typeof e.getInitPath!="function")throw new TypeError("options.getInitPath, when provided, must be a function.");if(e.onMaster!==void 0&&typeof e.onMaster!="function")throw new TypeError("options.onMaster, when provided, must be a function.");if(e.onPlaylist!==void 0&&typeof e.onPlaylist!="function")throw new TypeError("options.onPlaylist, when provided, must be a function.");if(e.onSegment!==void 0&&typeof e.onSegment!="function")throw new TypeError("options.onSegment, when provided, must be a function.");if(e.onInit!==void 0&&typeof e.onInit!="function")throw new TypeError("options.onInit, when provided, must be a function.");if(e.onSegmentPopped!==void 0&&typeof e.onSegmentPopped!="function")throw new TypeError("options.onSegmentPopped, when provided, must be a function.");super(),this._options=e}_createMuxer(e){return new el(e,this._options,t=>[new cu(t,this._options)])}get _name(){return"HTTP Live Streaming (HLS)"}get fileExtension(){return".m3u8"}get mimeType(){return cr}getSupportedCodecs(){let e=new Set(ot(this._options.segmentFormat).flatMap(t=>t.getSupportedCodecs()));for(let t of lo)e.delete(t);return this._options.singleFilePerPlaylist?e.delete("webvtt"):e.add("webvtt"),[...e]}getSupportedTrackCounts(){let e=!1,t=!1;for(let n of ot(this._options.segmentFormat)){let i=n.getSupportedTrackCounts();e||=i.video.max>0,t||=i.audio.max>0}return{video:{min:0,max:e?1/0:0},audio:{min:0,max:t?1/0:0},subtitle:{min:0,max:1/0},total:{min:0,max:1/0}}}get supportsVideoTransformationMetadata(){return ot(this._options.segmentFormat).some(e=>e.supportsVideoTransformationMetadata)}get supportsTimestampedMediaData(){return!0}get negativeTimestampSupport(){let e=ot(this._options.segmentFormat);return e.some(t=>t.negativeTimestampSupport==="none")?"none":e.some(t=>t.negativeTimestampSupport==="prefer-non-negative")?"prefer-non-negative":e.some(t=>t.negativeTimestampSupport==="full")?"full":null}_codecUnsupportedHint(e){return e==="webvtt"&&this._options.singleFilePerPlaylist?" WebVTT segments are raw text and cannot be addressed via byte ranges, unlike the fragmented MP4 that carries 'ttml' subtitle tracks. Use 'ttml', or disable `singleFilePerPlaylist`.":" Using different segment formats may grant support for this codec."}},pR=["segmentFormat","targetDuration","partDuration","singleFilePerPlaylist","live","maxLiveSegmentCount","getPlaylistPath","getSegmentPath","getInitPath","separateRenditions"],hR=r=>r.some(e=>e.negativeTimestampSupport==="none")?"none":r.some(e=>e.negativeTimestampSupport==="prefer-non-negative")?"prefer-non-negative":r.some(e=>e.negativeTimestampSupport==="full")?"full":null,fu=class extends nt{constructor(e){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(typeof e.mpdPath!="string"||e.mpdPath.length===0)throw new TypeError("options.mpdPath must be a non-empty string.");if(e.onMpd!==void 0&&typeof e.onMpd!="function")throw new TypeError("options.onMpd, when provided, must be a function.");if(e.singleFilePerPlaylist){let t=ot(e.segmentFormat).find(n=>!(n instanceof Ca)&&!n._isFragmentedIsobmff());if(t)throw new TypeError(`options.singleFilePerPlaylist is not supported with ${t._name} segments: single-file DASH addresses each representation's initialization by byte range, which only CMAF or fragmented-MP4 segments write.`)}super(),this._options=e}_createMuxer(e){return new el(e,this._options,t=>[new lu(t,this._options)])}get _name(){return"MPEG-DASH"}get fileExtension(){return".mpd"}get mimeType(){return"application/dash+xml"}getSupportedCodecs(){let e=new Set(ot(this._options.segmentFormat).flatMap(t=>t.getSupportedCodecs()));return this._options.singleFilePerPlaylist?e.delete("webvtt"):e.add("webvtt"),[...e]}_codecUnsupportedHint(e){return e==="webvtt"&&this._options.singleFilePerPlaylist?" WebVTT segments are raw text and cannot be addressed via byte ranges, unlike the fragmented MP4 that carries 'ttml' subtitle tracks. Use 'ttml', or disable `singleFilePerPlaylist`.":""}getSupportedTrackCounts(){let e=!1,t=!1;for(let n of ot(this._options.segmentFormat)){let i=n.getSupportedTrackCounts();e||=i.video.max>0,t||=i.audio.max>0}return{video:{min:0,max:e?1/0:0},audio:{min:0,max:t?1/0:0},subtitle:{min:0,max:1/0},total:{min:1,max:1/0}}}get supportsVideoTransformationMetadata(){return ot(this._options.segmentFormat).some(e=>e.supportsVideoTransformationMetadata)}get supportsTimestampedMediaData(){return ot(this._options.segmentFormat).some(e=>e.supportsTimestampedMediaData)}get negativeTimestampSupport(){return hR(ot(this._options.segmentFormat))}},Gf=class extends nt{constructor(e){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(!Array.isArray(e.formats)||e.formats.length===0)throw new TypeError("options.formats must be a non-empty array.");let t=e.formats.filter(a=>a instanceof mu),n=e.formats.filter(a=>a instanceof fu);if(t.length!==1)throw new TypeError("options.formats must contain exactly one HlsOutputFormat instance (the underlying muxer uses the HLS master playlist as its root file).");if(t.length+n.length!==e.formats.length)throw new TypeError("options.formats may currently only contain HlsOutputFormat or DashOutputFormat instances.");let i=t[0];for(let a of n)for(let s of pR)if(i._options[s]!==a._options[s])throw new TypeError(`options.formats: composed formats must agree on '${s}' \u2014 pass the same value (or instance) to every format.`);super(),this._options=e,this._hlsFormat=i,this._dashFormats=n}_createMuxer(e){return new el(e,this._hlsFormat._options,t=>[new cu(t,this._hlsFormat._options),...this._dashFormats.map(n=>new lu(t,n._options))])}get _name(){return"Adaptive Streaming (HLS + DASH)"}get fileExtension(){return".m3u8"}get mimeType(){return this._hlsFormat.mimeType}getSupportedCodecs(){return this._hlsFormat.getSupportedCodecs()}_trackTypeUnsupportedHint(e){return this._hlsFormat._trackTypeUnsupportedHint(e)}getSupportedTrackCounts(){return this._hlsFormat.getSupportedTrackCounts()}get supportsVideoTransformationMetadata(){return this._hlsFormat.supportsVideoTransformationMetadata}get supportsTimestampedMediaData(){return this._hlsFormat.supportsTimestampedMediaData}get negativeTimestampSupport(){return this._hlsFormat.negativeTimestampSupport}_codecUnsupportedHint(e){return this._hlsFormat._codecUnsupportedHint(e)}};var $f=["video","audio","subtitle"],As=class r{constructor(e,t,n,i,a){this.id=e,this.output=t,this.type=n,this.source=i,this.metadata=a}isVideoTrack(){return this.type==="video"}isAudioTrack(){return this.type==="audio"}isSubtitleTrack(){return this.type==="subtitle"}canBePairedWith(e){if(!(e instanceof r))throw new TypeError("other must be an OutputTrack.");if(this===e)return!1;let t=ot(this.metadata.group),n=ot(e.metadata.group);for(let i of t)if(this.type!==e.type&&n.some(o=>i===o)||n.some(o=>i._pairedGroups.has(o)))return!0;return!1}},pu=class extends As{constructor(e,t,n,i){super(e,t,"video",n,i)}},hu=class extends As{constructor(e,t,n,i){super(e,t,"audio",n,i)}},gu=class extends As{constructor(e,t,n,i){super(e,t,"subtitle",n,i)}},Pt=class r{constructor(){this._pairedGroups=new Set}pairWith(e){if(!(e instanceof r))throw new TypeError("other must be an OutputTrackGroup.");if(this===e)throw new TypeError("Cannot pair a group with itself.");this._pairedGroups.add(e),e._pairedGroups.add(this)}},cb=r=>{if(!r||typeof r!="object")throw new TypeError("metadata must be an object.");if(r.languageCode!==void 0&&!mn(r.languageCode))throw new TypeError("metadata.languageCode, when provided, must be a three-letter, ISO 639-2/T language code.");if(r.name!==void 0&&typeof r.name!="string")throw new TypeError("metadata.name, when provided, must be a string.");if(r.disposition!==void 0&&Dy(r.disposition),r.maximumPacketCount!==void 0&&(!Number.isInteger(r.maximumPacketCount)||r.maximumPacketCount<0))throw new TypeError("metadata.maximumPacketCount, when provided, must be a non-negative integer.");if(r.bitrate!==void 0&&(!Number.isFinite(r.bitrate)||r.bitrate<0))throw new TypeError("metadata.bitrate, when provided, must be a non-negative number.");if(r.averageBitrate!==void 0&&(!Number.isFinite(r.averageBitrate)||r.averageBitrate<0))throw new TypeError("metadata.averageBitrate, when provided, must be a non-negative number.");if(r.group!==void 0&&!(r.group instanceof Pt)&&(!Array.isArray(r.group)||r.group.some(e=>!(e instanceof Pt))))throw new TypeError("metadata.group, when provided, must be an OutputTrackGroup instance or an array of OutputTrackGroup instances.")},pr=class extends Lt{constructor(t){super();this.state="pending";this.defaultTrackGroup=new Pt;this.tracks=[];this._onFinalize=null;this._unfinalizedTargets=new Set;this._rootWriterPromise=null;this._startPromise=null;this._cancelPromise=null;this._finalizePromise=null;this._mutex=new vt;this._metadataTags={};this._rootTarget=null;this._rootTargetPromise=null;this._firstMediaStreamTimestamp=null;if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(!(t.format instanceof nt))throw new TypeError("options.format must be an OutputFormat.");if(!(t.target instanceof rt||t.target instanceof Je))throw new TypeError("options.target must be a Target or a PathedTarget.");if(t.target instanceof rt&&this._rememberTarget(t.target),t.initTarget!==void 0&&!(t.initTarget instanceof rt)&&typeof t.initTarget!="function")throw new Error("options.initTarget, when provided, must be a Target or a function that returns or resolves to a Target.");if(t.onFinalize!==void 0&&typeof t.onFinalize!="function")throw new TypeError("options.onFinalize, when provided, must be a function.");this.format=t.format,this._target=t.target,this._onFinalize=t.onFinalize??null,this._initTarget=t.initTarget??null,this._initTarget instanceof rt&&this._rememberTarget(this._initTarget),this._muxer=t.format._createMuxer(this)}get target(){let t="Output.target cannot be used when using PathedTarget with an async callback. Use the 'target' event instead.";if(this._rootTargetPromise)throw new TypeError(t);let n=this._getRootTarget();if(M(n))throw new TypeError(t);return n}_getTargetValidated(t){b(this._target instanceof Je);let n=this._target.getTarget(t),i=a=>{if(!(a instanceof rt))throw new TypeError("getTarget must return a Target.");return a};return M(n)?n.then(i):i(n)}async _getTarget(t){b(this._target instanceof Je);let n=await this._getTargetValidated(t);return this._emit("target",{target:n,request:t,isRoot:t.isRoot}),this.state==="canceled"?await n._close():this._rememberTarget(n),n}_rememberTarget(t){this._unfinalizedTargets.add(t),t.on("finalized",()=>this._unfinalizedTargets.delete(t),{once:!0})}async _getInitTarget(){if(b(this._initTarget!==null),this._initTarget instanceof rt)return this._initTarget;let t=await this._initTarget();return this.state==="canceled"?await t._close():this._rememberTarget(t),t}_hasInitTarget(){return this._initTarget!==null}_getRootTarget(){if(this._rootTarget)return this._rootTarget;if(this._rootTargetPromise)return this._rootTargetPromise;if(this._target instanceof rt)return this._emit("target",{target:this._target,request:null,isRoot:!0}),this._rootTarget=this._target,this._target;let t={path:this._target.rootPath,isRoot:!0,mimeType:this.format.mimeType},n=this._getTargetValidated(t),i=a=>(this.state==="canceled"?a._close():this._rememberTarget(a),this._emit("target",{target:a,request:t,isRoot:!0}),this._rootTarget=a,a);return M(n)?this._rootTargetPromise=n.then(i):i(n)}_getRootWriter(t){return this._rootWriterPromise??=(async()=>{let n=await this._getRootTarget(),i=new Br(n,typeof t=="boolean"?t:t(n));return i.start(),i})()}addVideoTrack(t,n={}){if(!(t instanceof Nn))throw new TypeError("source must be a VideoSource.");if(cb(n),n.rotation!==void 0&&![0,90,180,270].includes(n.rotation))throw new TypeError(`Invalid video rotation: ${n.rotation}. Has to be 0, 90, 180 or 270.`);if(n.flip!==void 0&&typeof n.flip!="boolean")throw new TypeError("metadata.flip, when provided, must be a boolean.");if(n.transformationMatrix!==void 0&&(!Array.isArray(n.transformationMatrix)||n.transformationMatrix.length!==9||!n.transformationMatrix.every(a=>Number.isFinite(a))))throw new TypeError("metadata.transformationMatrix, when provided, must be an array of 9 finite numbers.");if(n.frameRate!==void 0&&(!Number.isFinite(n.frameRate)||n.frameRate<=0))throw new TypeError(`Invalid video frame rate: ${n.frameRate}. Must be a positive number.`);if(n.hasOnlyKeyPackets!==void 0&&typeof n.hasOnlyKeyPackets!="boolean")throw new TypeError("metadata.hasOnlyKeyPackets, when provided, must be a boolean.");if(n.canBeTransparent!==void 0&&typeof n.canBeTransparent!="boolean")throw new TypeError("metadata.canBeTransparent, when provided, must be a boolean.");if(n.decoderConfig!==void 0&&Vn({decoderConfig:n.decoderConfig},t._codec),n.primingPacket!==void 0){if(!(n.primingPacket instanceof oe))throw new TypeError("metadata.primingPacket, when provided, must be an EncodedPacket.");if(n.decoderConfig===void 0)throw new TypeError("metadata.primingPacket can only be provided alongside metadata.decoderConfig.")}if(n.parameterSets!==void 0&&!["inBand","outOfBand"].includes(n.parameterSets))throw new TypeError(`Invalid parameter set placement: ${n.parameterSets}. Must be 'inBand' or 'outOfBand'.`);if(n.dolbyVision!==void 0&&(Xu(n.dolbyVision,"metadata.dolbyVision"),t._codec!=="avc"&&t._codec!=="hevc"))throw new Error(`metadata.dolbyVision was provided, but ${t._codec} cannot carry a Dolby Vision configuration record. Dolby Vision rides on AVC or HEVC.`);if(n.closedCaptions!==void 0&&(Cw(n.closedCaptions,"metadata.closedCaptions"),t._codec!=="avc"&&t._codec!=="hevc"))throw new Error(`metadata.closedCaptions was provided, but ${t._codec} has no bitstream that can carry them. Closed captions ride in AVC or HEVC SEI messages.`);let i={...n};return i.group??=this.defaultTrackGroup,this._addTrack(new pu(this.tracks.length+1,this,t,i))}addAudioTrack(t,n={}){if(!(t instanceof Ln))throw new TypeError("source must be an AudioSource.");if(cb(n),n.decoderConfig!==void 0&&tt({decoderConfig:n.decoderConfig},t._codec),n.primingPacket!==void 0){if(!(n.primingPacket instanceof oe))throw new TypeError("metadata.primingPacket, when provided, must be an EncodedPacket.");if(n.decoderConfig===void 0)throw new TypeError("metadata.primingPacket can only be provided alongside metadata.decoderConfig.")}let i={...n};return i.group??=this.defaultTrackGroup,this._addTrack(new hu(this.tracks.length+1,this,t,i))}addSubtitleTrack(t,n={}){if(!(t instanceof wa))throw new TypeError("source must be a SubtitleSource.");cb(n);let i={...n};return i.group??=this.defaultTrackGroup,this._addTrack(new gu(this.tracks.length+1,this,t,i))}setMetadataTags(t){if(yl(t),this.state!=="pending")throw new Error("Cannot set metadata tags after output has been started or canceled.");this._metadataTags=t}_addTrack(t){if(this.state!=="pending")throw new Error("Cannot add track after output has been started or canceled.");if(t.source._connectedTrack)throw new Error("Source is already used for a track.");let n=this.format.getSupportedTrackCounts(),i=this.tracks.reduce((o,l)=>o+(l.type===t.type?1:0),0),a=n[t.type].max;if(i===a)throw new Error(a===0?`${this.format._name} does not support ${t.type} tracks.`+this.format._trackTypeUnsupportedHint(t.type):`${this.format._name} does not support more than ${a} ${t.type} track${a===1?"":"s"}.`);let s=n.total.max;if(this.tracks.length===s)throw new Error(`${this.format._name} does not support more than ${s} tracks${s===1?"":"s"} in total.`);if(t.isVideoTrack()){let o=this.format.getSupportedVideoCodecs();if(o.length===0)throw new Error(`${this.format._name} does not support video tracks.`+this.format._codecUnsupportedHint(t.source._codec));if(!o.includes(t.source._codec))throw new Error(`Codec '${t.source._codec}' cannot be contained within ${this.format._name}. Supported video codecs are: ${o.map(l=>`'${l}'`).join(", ")}.`+this.format._codecUnsupportedHint(t.source._codec))}else if(t.isAudioTrack()){let o=this.format.getSupportedAudioCodecs();if(o.length===0)throw new Error(`${this.format._name} does not support audio tracks.`+this.format._codecUnsupportedHint(t.source._codec));if(!o.includes(t.source._codec))throw new Error(`Codec '${t.source._codec}' cannot be contained within ${this.format._name}. Supported audio codecs are: ${o.map(l=>`'${l}'`).join(", ")}.`+this.format._codecUnsupportedHint(t.source._codec))}else if(t.isSubtitleTrack()){let o=this.format.getSupportedSubtitleCodecs();if(o.length===0)throw new Error(`${this.format._name} does not support subtitle tracks.`+this.format._codecUnsupportedHint(t.source._codec));if(!o.includes(t.source._codec))throw new Error(`Codec '${t.source._codec}' cannot be contained within ${this.format._name}. Supported subtitle codecs are: ${o.map(l=>`'${l}'`).join(", ")}.`+this.format._codecUnsupportedHint(t.source._codec))}return this.tracks.push(t),t.source._connectedTrack=t,t}hasEnoughTracks(){let t=this.format.getSupportedTrackCounts();for(let i of $f){let a=this.tracks.reduce((o,l)=>o+(l.type===i?1:0),0),s=t[i].min;if(a<s)return!1}let n=t.total.min;return!(this.tracks.length<n)}async start(){let t=this.format.getSupportedTrackCounts();for(let i of $f){let a=this.tracks.reduce((o,l)=>o+(l.type===i?1:0),0),s=t[i].min;if(a<s)throw new Error(s===t[i].max?`${this.format._name} requires exactly ${s} ${i} track${s===1?"":"s"}.`:`${this.format._name} requires at least ${s} ${i} track${s===1?"":"s"}.`)}let n=t.total.min;if(this.tracks.length<n)throw new Error(n===t.total.max?`${this.format._name} requires exactly ${n} track${n===1?"":"s"}.`:`${this.format._name} requires at least ${n} track${n===1?"":"s"}.`);if(this.state==="canceled")throw new Error("Output has been canceled.");return this._startPromise?(N._warn("Output has already been started."),this._startPromise):this._startPromise=(async()=>{this.state="started";let i=this._mutex.acquire();try{await this._muxer.start();let a=this.tracks.map(s=>s.source._start());await Promise.all(a)}finally{(await i)()}})()}getMimeType(){return this._muxer.getMimeType()}async cancel(){if(this.state==="canceled")return this._cancelPromise??void 0;if(this.state==="finalizing"||this.state==="finalized"){this.state==="finalized"&&N._warn("Output has already been finalized.");return}return this._cancelPromise=(async()=>{this.state="canceled";let t=await this._mutex.acquire();try{let n=this.tracks.map(i=>i.source._flushOrWaitForOngoingClose(!0));await Promise.all(n),await Promise.all([...this._unfinalizedTargets].map(i=>i._close())),this._unfinalizedTargets.clear()}finally{t()}})()}async finalize(){if(this.state==="pending")throw new Error("Cannot finalize before starting.");if(this.state==="canceled")throw new Error("Cannot finalize after canceling.");return this._finalizePromise?(N._warn("Output has already been finalized."),this._finalizePromise):this._finalizePromise=(async()=>{this.state="finalizing";let t=await this._mutex.acquire();try{let n=this.tracks.map(i=>i.source._flushOrWaitForOngoingClose(!1));if(await Promise.all(n),await this._muxer.finalize(),this._rootWriterPromise){let i=await this._rootWriterPromise;i.finalized||(await i.flush(),await i.finalize())}this._onFinalize&&await this._onFinalize(),this.state="finalized"}catch(n){throw this.state="canceled",n}finally{await Promise.all([...this._unfinalizedTargets].map(n=>n._close().catch(()=>{}))),this._unfinalizedTargets.clear(),t()}})()}};var Xf=r=>{if(!r||typeof r!="object")throw new TypeError("options.video, when provided, must be an object.");if(r?.discard!==void 0&&typeof r.discard!="boolean")throw new TypeError("options.video.discard, when provided, must be a boolean.");if(r?.forceTranscode!==void 0&&typeof r.forceTranscode!="boolean")throw new TypeError("options.video.forceTranscode, when provided, must be a boolean.");if(r?.codec!==void 0&&!Te.includes(r.codec))throw new TypeError(`options.video.codec, when provided, must be one of: ${Te.join(", ")}.`);let e=r?.bitrate;if(r?.quality!==void 0&&!(r.quality instanceof Pe))throw new TypeError("options.video.quality, when provided, must be a Quality.");if(r?.quality!==void 0&&e!==void 0)throw new TypeError("options.video.quality and options.video.bitrate cannot both be provided.");if(e!==void 0&&!(e instanceof Pe)&&(!Number.isInteger(e)||e<=0))throw new TypeError("options.video.bitrate, when provided, must be a positive integer or a quality.");if(r?.width!==void 0&&(!Number.isInteger(r.width)||r.width<=0))throw new TypeError("options.video.width, when provided, must be a positive integer.");if(r?.height!==void 0&&(!Number.isInteger(r.height)||r.height<=0))throw new TypeError("options.video.height, when provided, must be a positive integer.");if(r?.fit!==void 0&&!["fill","contain","cover"].includes(r.fit))throw new TypeError("options.video.fit, when provided, must be one of 'fill', 'contain', or 'cover'.");if(r?.width!==void 0&&r.height!==void 0&&r.fit===void 0)throw new TypeError("When both options.video.width and options.video.height are provided, options.video.fit must also be provided.");if(r?.rotate!==void 0&&![0,90,180,270].includes(r.rotate))throw new TypeError("options.video.rotate, when provided, must be 0, 90, 180 or 270.");if(r?.flip!==void 0&&typeof r.flip!="boolean")throw new TypeError("options.video.flip, when provided, must be a boolean.");if(r?.allowTransformationMetadata!==void 0&&typeof r.allowTransformationMetadata!="boolean")throw new TypeError("options.video.allowTransformationMetadata, when provided, must be a boolean.");if(r?.allowRotationMetadata!==void 0&&typeof r.allowRotationMetadata!="boolean")throw new TypeError("options.video.allowRotationMetadata, when provided, must be a boolean.");if(r?.crop!==void 0&&ga(r.crop,"options.video."),r?.frameRate!==void 0&&(!Number.isFinite(r.frameRate)||r.frameRate<=0))throw new TypeError("options.video.frameRate, when provided, must be a finite positive number.");if(r?.alpha!==void 0&&!["discard","keep"].includes(r.alpha))throw new TypeError("options.video.alpha, when provided, must be either 'discard' or 'keep'.");if(r?.keyFrameInterval!==void 0&&(!Number.isFinite(r.keyFrameInterval)||r.keyFrameInterval<0))throw new TypeError("options.video.keyFrameInterval, when provided, must be a non-negative number.");if(r?.parameterSets!==void 0&&!["inBand","outOfBand"].includes(r.parameterSets))throw new TypeError("options.video.parameterSets, when provided, must be 'inBand' or 'outOfBand'.");if(r?.bitDepth!==void 0&&!ba.includes(r.bitDepth))throw new TypeError(`options.video.bitDepth, when provided, must be one of ${ba.join(", ")}.`);if(r?.colorSpace!==void 0&&Wc(r.colorSpace,"options.video.colorSpace"),r?.dolbyVision!==void 0&&(Xu(r.dolbyVision,"options.video.dolbyVision"),r.dolbyVision.blSignalCompatibilityId===0))throw new Error("options.video.dolbyVision states a base layer that is not cross-compatible (blSignalCompatibilityId 0, profile 5), whose IPT-PQ-c2 base an encoder cannot produce.");if(r?.hdrStaticMetadata!==void 0&&Km(r.hdrStaticMetadata,"options.video.hdrStaticMetadata"),Xm(r?.bitDepth,r?.colorSpace,"options.video."),Qm(r?.hdrStaticMetadata,r?.colorSpace,"options.video."),r?.process!==void 0&&typeof r.process!="function")throw new TypeError("options.video.process, when provided, must be a function.");if(r?.preProcess!==void 0&&typeof r.preProcess!="function")throw new TypeError("options.video.preProcess, when provided, must be a function.");if(r?.preProcessFlush!==void 0&&typeof r.preProcessFlush!="function")throw new TypeError("options.video.preProcessFlush, when provided, must be a function.");if(r?.processFlush!==void 0&&typeof r.processFlush!="function")throw new TypeError("options.video.processFlush, when provided, must be a function.");if(r?.processedWidth!==void 0&&(!Number.isInteger(r.processedWidth)||r.processedWidth<=0))throw new TypeError("options.video.processedWidth, when provided, must be a positive integer.");if(r?.processedHeight!==void 0&&(!Number.isInteger(r.processedHeight)||r.processedHeight<=0))throw new TypeError("options.video.processedHeight, when provided, must be a positive integer.");if(r?.hardwareAcceleration!==void 0&&!["no-preference","prefer-hardware","prefer-software"].includes(r.hardwareAcceleration))throw new TypeError("options.video.hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.");if(r?.group!==void 0&&!(r.group instanceof Pt||Array.isArray(r.group)&&r.group.every(t=>t instanceof Pt)))throw new TypeError("options.video.group, when provided, must be an OutputTrackGroup or an array of OutputTrackGroups.");if(r?.maximumPacketCount!==void 0&&(!Number.isInteger(r.maximumPacketCount)||r.maximumPacketCount<0))throw new TypeError("options.video.maximumPacketCount, when provided, must be a non-negative integer.")},Kf=r=>{if(!r||typeof r!="object")throw new TypeError("options.audio, when provided, must be an object.");if(r?.discard!==void 0&&typeof r.discard!="boolean")throw new TypeError("options.audio.discard, when provided, must be a boolean.");if(r?.forceTranscode!==void 0&&typeof r.forceTranscode!="boolean")throw new TypeError("options.audio.forceTranscode, when provided, must be a boolean.");if(r?.codec!==void 0&&!Ee.includes(r.codec))throw new TypeError(`options.audio.codec, when provided, must be one of: ${Ee.join(", ")}.`);let e=r?.bitrate;if(r?.quality!==void 0&&!(r.quality instanceof Pe))throw new TypeError("options.audio.quality, when provided, must be a Quality.");if(r?.quality!==void 0&&e!==void 0)throw new TypeError("options.audio.quality and options.audio.bitrate cannot both be provided.");if(e!==void 0&&!(e instanceof Pe)&&(!Number.isInteger(e)||e<=0))throw new TypeError("options.audio.bitrate, when provided, must be a positive integer or a quality.");if(r?.numberOfChannels!==void 0&&(!Number.isInteger(r.numberOfChannels)||r.numberOfChannels<=0))throw new TypeError("options.audio.numberOfChannels, when provided, must be a positive integer.");if(r?.sampleRate!==void 0&&(!Number.isInteger(r.sampleRate)||r.sampleRate<=0))throw new TypeError("options.audio.sampleRate, when provided, must be a positive integer.");if(r?.sampleFormat!==void 0&&!["u8","s16","s32","f32"].includes(r.sampleFormat))throw new TypeError("options.audio.sampleFormat, when provided, must be one of: u8, s16, s32, f32.");if(r?.process!==void 0&&typeof r.process!="function")throw new TypeError("options.audio.process, when provided, must be a function.");if(r?.processedNumberOfChannels!==void 0&&(!Number.isInteger(r.processedNumberOfChannels)||r.processedNumberOfChannels<=0))throw new TypeError("options.audio.processedNumberOfChannels, when provided, must be a positive integer.");if(r?.processedSampleRate!==void 0&&(!Number.isInteger(r.processedSampleRate)||r.processedSampleRate<=0))throw new TypeError("options.audio.processedSampleRate, when provided, must be a positive integer.");if(r?.group!==void 0&&!(r.group instanceof Pt||Array.isArray(r.group)&&r.group.every(t=>t instanceof Pt)))throw new TypeError("options.audio.group, when provided, must be an OutputTrackGroup or an array of OutputTrackGroups.");if(r?.maximumPacketCount!==void 0&&(!Number.isInteger(r.maximumPacketCount)||r.maximumPacketCount<0))throw new TypeError("options.audio.maximumPacketCount, when provided, must be a non-negative integer.")},Qf=r=>{if(!r||typeof r!="object")throw new TypeError("options.subtitle, when provided, must be an object.");if(r?.discard!==void 0&&typeof r.discard!="boolean")throw new TypeError("options.subtitle.discard, when provided, must be a boolean.");if(r?.codec!==void 0&&!Mt.includes(r.codec))throw new TypeError(`options.subtitle.codec, when provided, must be one of: ${Mt.join(", ")}.`);if(r?.group!==void 0&&!(r.group instanceof Pt||Array.isArray(r.group)&&r.group.every(e=>e instanceof Pt)))throw new TypeError("options.subtitle.group, when provided, must be an OutputTrackGroup or an array of OutputTrackGroups.")},ub=2,db=48e3,jk=256,rl=class r{constructor(e){this._state="idle";this._timestampOffset=0;this._timestampOffsetAdjusted=!1;this._copyTimestampPossible=new Map;this._copyStartPackets=new Map;this._trackDurations=new Map;this._nextOutputTrackId=0;this._outputTrackIds=[];this._outputOwnTrackGroups=[];this._trackPumps=[];this._composable=!1;this._executed=!1;this._executionUntil=1/0;this._finishRequested=!1;this._pauseRequested=!1;this._synchronizer=new mb(this);this._totalDuration=null;this._maxTimestamps=new Map;this.onProgress=void 0;this._computeProgress=!1;this._lastProgress=0;this._undecodableSourceCodecs=[];this.isValid=!1;this.utilizedTracks=[];this.discardedTracks=[];if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(!(e.input instanceof _n))throw new TypeError("options.input must be an Input.");if(!(e.output instanceof pr))throw new TypeError("options.output must be an Output.");if(e.tracks!==void 0&&e.tracks!=="all"&&e.tracks!=="primary")throw new TypeError("options.tracks, when provided, must be either 'all' or 'primary'.");if(e.composable!==void 0&&typeof e.composable!="boolean")throw new TypeError("options.composable, when provided, must be a boolean.");if(e.copy!==void 0&&e.copy!==!1){if(!e.copy||typeof e.copy!="object")throw new TypeError("options.copy, when provided, must be an object or false.");if(e.copy.mode!==void 0&&!["forced","preferred"].includes(e.copy.mode))throw new TypeError("options.copy.mode, when provided, must be 'forced' or 'preferred'.");if(e.copy.shiftTolerance!==void 0&&(!Ve(e.copy.shiftTolerance)||e.copy.shiftTolerance<0))throw new TypeError("options.copy.shiftTolerance, when provided, must be a non-negative number.");if(e.copy.boundaryPolicy!==void 0&&!["expand","shrink"].includes(e.copy.boundaryPolicy))throw new TypeError("options.copy.boundaryPolicy, when provided, must be 'expand' or 'shrink'.");if(e.copy.boundaryTolerance!==void 0&&(!Ve(e.copy.boundaryTolerance)||e.copy.boundaryTolerance<0))throw new TypeError("options.copy.boundaryTolerance, when provided, must be a non-negative number.")}let t=e.composable??!1;if(t){if(e.tags!==void 0)throw new TypeError("options.tags cannot be set by a composable conversion; set metadata directly on the output instead.");if(e.output.state!=="pending")throw new TypeError("options.output must not have been started yet.")}else if(e.output.tracks.length>0||Object.keys(e.output._metadataTags).length>0||e.output.state!=="pending")throw new TypeError("options.output must be fresh: no tracks or metadata tags added and not started.");if(e.video!==void 0&&typeof e.video!="function")if(Array.isArray(e.video))for(let n of e.video)Xf(n);else Xf(e.video);if(e.audio!==void 0&&typeof e.audio!="function")if(Array.isArray(e.audio))for(let n of e.audio)Kf(n);else Kf(e.audio);if(e.subtitle!==void 0&&typeof e.subtitle!="function")if(Array.isArray(e.subtitle))for(let n of e.subtitle)Qf(n);else Qf(e.subtitle);if(e.trim!==void 0&&(!e.trim||typeof e.trim!="object"))throw new TypeError("options.trim, when provided, must be an object.");if(e.trim?.start!==void 0&&!Number.isFinite(e.trim.start))throw new TypeError("options.trim.start, when provided, must be a finite number.");if(e.trim?.end!==void 0&&!Ve(e.trim.end))throw new TypeError("options.trim.end, when provided, must be a number.");if(e.trim?.start!==void 0&&e.trim.end!==void 0&&e.trim.start>=e.trim.end)throw new TypeError("options.trim.start must be less than options.trim.end.");if(e.tags!==void 0&&(typeof e.tags!="object"||!e.tags)&&typeof e.tags!="function")throw new TypeError("options.tags, when provided, must be an object or a function.");if(typeof e.tags=="object"&&yl(e.tags),e.showWarnings!==void 0&&typeof e.showWarnings!="boolean")throw new TypeError("options.showWarnings, when provided, must be a boolean.");this._options=e,this._copyMode=e.copy===!1?!1:e.copy?.mode??"preferred",this._copyTimestampShiftTolerance=e.copy===!1?0:e.copy?.shiftTolerance??0,this._copyBoundaryPolicy=e.copy===!1?"expand":e.copy?.boundaryPolicy??"expand",this._copyBoundaryTolerance=e.copy===!1?1/0:e.copy?.boundaryTolerance??1/0,this._composable=t,this.input=e.input,this.output=e.output}get state(){return this._state}static async init(e){let t=new r(e);return await t._init(),t}async _init(){let e=await this.input.getFormat(),t,n=this._options.tracks;if(n===void 0&&(n=e.name.includes("(HLS)")?"primary":"all"),n==="all")t=await this.input.getTracks();else if(n==="primary"){let u=await this.input.getPrimaryVideoTrack(),d=await this.input.getPrimaryAudioTrack();t=[u,d].filter(m=>m!==null);for(let m of await this.input.getSubtitleTracks())this.discardedTracks.push({track:m,reason:"not_a_primary_track",trackOptions:{}})}else be(n),b(!1);let i=this.output.format.getSupportedTrackCounts(),a=1,s=1,o=1,l=[],c=[];for(let u of t){let d;if(u.isVideoTrack())if(this._options.video)if(typeof this._options.video=="function"){let p=await this._options.video(u,a)??{};if(Array.isArray(p))for(let g of p)Xf(g);else Xf(p);d=Array.isArray(p)?p:[p],a++}else d=Array.isArray(this._options.video)?this._options.video:[this._options.video];else d=[{}];else if(u.isAudioTrack())if(this._options.audio)if(typeof this._options.audio=="function"){let p=await this._options.audio(u,s)??{};if(Array.isArray(p))for(let g of p)Kf(g);else Kf(p);d=Array.isArray(p)?p:[p],s++}else d=Array.isArray(this._options.audio)?this._options.audio:[this._options.audio];else d=[{}];else if(u.isSubtitleTrack())if(this._options.subtitle)if(typeof this._options.subtitle=="function"){let p=await this._options.subtitle(u,o)??{};if(Array.isArray(p))for(let g of p)Qf(g);else Qf(p);d=Array.isArray(p)?p:[p],o++}else d=Array.isArray(this._options.subtitle)?this._options.subtitle:[this._options.subtitle];else d=[{}];else b(!1);let m=d.filter(p=>p.discard);for(let p of m)this.discardedTracks.push({track:u,reason:"discarded_by_user",trackOptions:p});if(d.length===m.length){d.length===0&&this.discardedTracks.push({track:u,reason:"discarded_by_user",trackOptions:{}});continue}let f=d.filter(p=>!p.discard);l.push(u),c.push(f)}this._options.trim?.start!==void 0?this._startTimestamp=this._options.trim.start:this._startTimestamp=Math.max(await this.input.getFirstTimestamp(l),0),this._endTimestamp=Math.max(this._options.trim?.end??1/0,this._startTimestamp),this._timestampOffset=-this._startTimestamp;for(let u=0;u<l.length;u++){let d=l[u],m=c[u];for(let f of m){if(this.output.tracks.length===i.total.max){this.discardedTracks.push({track:d,reason:"max_track_count_reached",trackOptions:f});continue}if(this.output.tracks.reduce((h,y)=>h+(y.type===d.type?1:0),0)===i[d.type].max){this.discardedTracks.push({track:d,reason:"max_track_count_of_type_reached",trackOptions:f});continue}let g=this._nextOutputTrackId++;d.isVideoTrack()?await this._processVideoTrack(d,f,g):d.isAudioTrack()?await this._processAudioTrack(d,f,g):d.isSubtitleTrack()?await this._processSubtitleTrack(d,f,g):b(!1)}}for(let u=0;u<this.utilizedTracks.length-1;u++)for(let d=u+1;d<this.utilizedTracks.length;d++){let m=this.utilizedTracks[u],f=this.utilizedTracks[d],p=this._outputOwnTrackGroups[u],g=this._outputOwnTrackGroups[d];b(p!==void 0),b(g!==void 0),p&&g&&m.canBePairedWith(f)&&p.pairWith(g)}if(!this._composable){let u={...await this.input.getMetadataTags()};delete u.creationTime;let d;if(this._options.tags){let p=typeof this._options.tags=="function"?await this._options.tags(u):this._options.tags;yl(p),d=p}else d=u;let m=e.mimeType===this.output.format.mimeType;u.raw===d.raw&&!m&&delete d.raw,this.output.setMetadataTags(d)}if(this._composable?this.isValid=!0:this.isValid=this.output.hasEnoughTracks()&&this.output.tracks.length>0,this._options.showWarnings??!0){let u=[],d=this.discardedTracks.filter(m=>m.reason!=="discarded_by_user");d.length>0&&(u.push("Some tracks had to be discarded from the conversion:",d),_y()&&d.some(m=>m.reason==="undecodable_source_codec")&&u.push(`
|
|
76
|
+
`;return s},Lf=class extends Ke{constructor(){super(...arguments);this.cues=[];this.segmentStartTimestamp=0;this.preamble=null}async start(){this.writer=await this.output._getRootWriter(!0)}async getMimeType(){return lb}async addEncodedVideoPacket(){throw new E("WebVTT does not support video.")}async addEncodedAudioPacket(){throw new E("WebVTT does not support audio.")}async addSubtitleCue(t,n,i){let a=await this.mutex.acquire();try{this.preamble??=i?.config?.description??null,this.cues.push(n)}finally{a()}}async finalize(){let t=await this.mutex.acquire();try{this.writer.write(re.encode(fR({preamble:this.preamble,startTimestamp:this.segmentStartTimestamp,cues:this.cues}))),await this.writer.flush()}finally{t()}}};var nt=class{get supportsVideoRotationMetadata(){return this.supportsVideoTransformationMetadata}get requiresMaximumPacketCount(){return!1}getSupportedVideoCodecs(){return this.getSupportedCodecs().filter(e=>Te.includes(e))}getSupportedAudioCodecs(){return this.getSupportedCodecs().filter(e=>Ee.includes(e))}getSupportedSubtitleCodecs(){return this.getSupportedCodecs().filter(e=>Mt.includes(e))}_codecUnsupportedHint(e){return""}_trackTypeUnsupportedHint(e){return""}_isFragmentedIsobmff(){return!1}},hi=class extends nt{constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.fastStart!==void 0&&![!1,"in-memory","reserve","fragmented"].includes(e.fastStart))throw new TypeError("options.fastStart, when provided, must be false, 'in-memory', 'reserve', or 'fragmented'.");if(e.minimumFragmentDuration!==void 0&&(!Ve(e.minimumFragmentDuration)||e.minimumFragmentDuration<0))throw new TypeError("options.minimumFragmentDuration, when provided, must be a non-negative number.");if(e.segmentIndex!==void 0&&typeof e.segmentIndex!="boolean")throw new TypeError("options.segmentIndex, when provided, must be a boolean.");if(e.onFtyp!==void 0&&typeof e.onFtyp!="function")throw new TypeError("options.onFtyp, when provided, must be a function.");if(e.onMoov!==void 0&&typeof e.onMoov!="function")throw new TypeError("options.onMoov, when provided, must be a function.");if(e.onMdat!==void 0&&typeof e.onMdat!="function")throw new TypeError("options.onMdat, when provided, must be a function.");if(e.onMoof!==void 0&&typeof e.onMoof!="function")throw new TypeError("options.onMoof, when provided, must be a function.");if(e.metadataFormat!==void 0&&!["mdir","mdta","udta","auto"].includes(e.metadataFormat))throw new TypeError("options.metadataFormat, when provided, must be either 'auto', 'mdir', 'mdta', or 'udta'.");super(),this._options=e}getSupportedTrackCounts(){return{video:{min:0,max:4294967295},audio:{min:0,max:4294967295},subtitle:{min:0,max:4294967295},total:{min:0,max:4294967295}}}get supportsVideoTransformationMetadata(){return!0}get supportsTimestampedMediaData(){return!0}get negativeTimestampSupport(){return"full"}get requiresMaximumPacketCount(){return this._options.fastStart==="reserve"}_createMuxer(e){return new ps(e,this)}_isFragmentedIsobmff(){return this._options.fastStart==="fragmented"}},ks=class extends hi{constructor(e){super(e)}get _name(){return"MP4"}get fileExtension(){return".mp4"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...Te,...rn,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...Mt]}_codecUnsupportedHint(e){return new gi().getSupportedCodecs().includes(e)?" Switching to MOV will grant support for this codec.":""}},Ca=class extends hi{constructor(e){super(e)}get _name(){return"CMAF"}get fileExtension(){return".m4s"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...Te,...rn,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...Mt]}},gi=class extends hi{constructor(e){super(e)}get _name(){return"MOV"}get fileExtension(){return".mov"}get mimeType(){return"video/quicktime"}getSupportedCodecs(){return[...Te,...Ee]}_codecUnsupportedHint(e){return new ks().getSupportedCodecs().includes(e)?" Switching to MP4 will grant support for this codec.":""}},tl=class extends nt{constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.appendOnly!==void 0&&typeof e.appendOnly!="boolean")throw new TypeError("options.appendOnly, when provided, must be a boolean.");if(e.minimumClusterDuration!==void 0&&(!Ve(e.minimumClusterDuration)||e.minimumClusterDuration<0))throw new TypeError("options.minimumClusterDuration, when provided, must be a non-negative number.");if(e.onEbmlHeader!==void 0&&typeof e.onEbmlHeader!="function")throw new TypeError("options.onEbmlHeader, when provided, must be a function.");if(e.onSegmentHeader!==void 0&&typeof e.onSegmentHeader!="function")throw new TypeError("options.onHeader, when provided, must be a function.");if(e.onCluster!==void 0&&typeof e.onCluster!="function")throw new TypeError("options.onCluster, when provided, must be a function.");super(),this._options=e}_createMuxer(e){return new gf(e,this)}get _name(){return"Matroska"}getSupportedTrackCounts(){return{video:{min:0,max:127},audio:{min:0,max:127},subtitle:{min:0,max:127},total:{min:0,max:127}}}get fileExtension(){return".mkv"}get mimeType(){return"video/x-matroska"}getSupportedCodecs(){return[...Te,...rn,...Se.filter(e=>!["pcm-s8","pcm-f32be","pcm-f64be","ulaw","alaw"].includes(e)),"webvtt"]}get supportsVideoTransformationMetadata(){return!1}get supportsTimestampedMediaData(){return!0}get negativeTimestampSupport(){return"prefer-non-negative"}},Ia=class extends tl{constructor(e){super(e)}getSupportedCodecs(){return[...Te.filter(e=>["vp8","vp9","av1"].includes(e)),...Ee.filter(e=>["opus","vorbis"].includes(e)),"webvtt"]}get _name(){return"WebM"}get fileExtension(){return".webm"}get mimeType(){return"video/webm"}_codecUnsupportedHint(e){return new tl().getSupportedCodecs().includes(e)?" Switching to MKV will grant support for this codec.":""}},Vf=class extends nt{constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.xingHeader!==void 0&&typeof e.xingHeader!="boolean")throw new TypeError("options.xingHeader, when provided, must be a boolean.");if(e.onXingFrame!==void 0&&typeof e.onXingFrame!="function")throw new TypeError("options.onXingFrame, when provided, must be a function.");super(),this._options=e}_createMuxer(e){return new yf(e,this)}get _name(){return"MP3"}getSupportedTrackCounts(){return{video:{min:0,max:0},audio:{min:1,max:1},subtitle:{min:0,max:0},total:{min:1,max:1}}}get fileExtension(){return".mp3"}get mimeType(){return"audio/mpeg"}getSupportedCodecs(){return["mp3"]}get supportsVideoTransformationMetadata(){return!1}get supportsTimestampedMediaData(){return!1}get negativeTimestampSupport(){return null}},zf=class extends nt{constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.large!==void 0&&typeof e.large!="boolean")throw new TypeError("options.large, when provided, must be a boolean.");if(e.metadataFormat!==void 0&&!["info","id3"].includes(e.metadataFormat))throw new TypeError("options.metadataFormat, when provided, must be either 'info' or 'id3'.");if(e.onHeader!==void 0&&typeof e.onHeader!="function")throw new TypeError("options.onHeader, when provided, must be a function.");super(),this._options=e}_createMuxer(e){return new Af(e,this)}get _name(){return"WAVE"}getSupportedTrackCounts(){return{video:{min:0,max:0},audio:{min:1,max:1},subtitle:{min:0,max:0},total:{min:1,max:1}}}get fileExtension(){return".wav"}get mimeType(){return"audio/wav"}getSupportedCodecs(){return[...Se.filter(e=>["pcm-s16","pcm-s24","pcm-s32","pcm-f32","pcm-f64","pcm-u8","ulaw","alaw"].includes(e))]}get supportsVideoTransformationMetadata(){return!1}get supportsTimestampedMediaData(){return!1}get negativeTimestampSupport(){return null}},Hf=class extends nt{constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.maximumPageDuration!==void 0&&(!Ve(e.maximumPageDuration)||e.maximumPageDuration<=0))throw new TypeError("options.maximumPageDuration, when provided, must be a positive number.");if(e.maxInterleaveDelta!==void 0&&!(e.maxInterleaveDelta>0))throw new TypeError("options.maxInterleaveDelta, when provided, must be a positive number.");if(e.onPage!==void 0&&typeof e.onPage!="function")throw new TypeError("options.onPage, when provided, must be a function.");super(),this._options=e}_createMuxer(e){return new Sf(e,this)}get _name(){return"Ogg"}getSupportedTrackCounts(){return{video:{min:0,max:0},audio:{min:0,max:4294967296},subtitle:{min:0,max:0},total:{min:0,max:4294967296}}}get fileExtension(){return".ogg"}get mimeType(){return"application/ogg"}getSupportedCodecs(){return[...Ee.filter(e=>["vorbis","opus"].includes(e))]}get supportsVideoTransformationMetadata(){return!1}get supportsTimestampedMediaData(){return!0}get negativeTimestampSupport(){return"none"}},Wf=class extends nt{constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.onFrame!==void 0&&typeof e.onFrame!="function")throw new TypeError("options.onFrame, when provided, must be a function.");super(),this._options=e}_createMuxer(e){return new cf(e,this)}get _name(){return"ADTS"}getSupportedTrackCounts(){return{video:{min:0,max:0},audio:{min:1,max:1},subtitle:{min:0,max:0},total:{min:1,max:1}}}get fileExtension(){return".aac"}get mimeType(){return"audio/aac"}getSupportedCodecs(){return["aac"]}get supportsVideoTransformationMetadata(){return!1}get supportsTimestampedMediaData(){return!1}get negativeTimestampSupport(){return null}},qf=class extends nt{constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.appendOnly!==void 0&&typeof e.appendOnly!="boolean")throw new TypeError("options.appendOnly, when provided, must be a boolean.");super(),this._options=e}_createMuxer(e){return new uf(e,this)}get _name(){return"FLAC"}getSupportedTrackCounts(){return{video:{min:0,max:0},audio:{min:1,max:1},subtitle:{min:0,max:0},total:{min:1,max:1}}}get fileExtension(){return".flac"}get mimeType(){return"audio/flac"}getSupportedCodecs(){return["flac"]}get supportsVideoTransformationMetadata(){return!1}get supportsTimestampedMediaData(){return!1}get negativeTimestampSupport(){return null}},ws=class extends nt{constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.timestampOffset!==void 0&&(!Number.isFinite(e.timestampOffset)||e.timestampOffset<0))throw new TypeError("options.timestampOffset, when provided, must be a non-negative number.");if(e.scte35Pid!==void 0&&(!Number.isInteger(e.scte35Pid)||e.scte35Pid<16||e.scte35Pid>8190))throw new TypeError("options.scte35Pid, when provided, must be an integer between 0x0010 and 0x1ffe.");if(e.tableRepeatInterval!==void 0&&!(e.tableRepeatInterval>0))throw new TypeError("options.tableRepeatInterval, when provided, must be a positive number.");if(e.privateStreams!==void 0){if(!Array.isArray(e.privateStreams))throw new TypeError("options.privateStreams, when provided, must be an array.");let t=new Set;for(let n of e.privateStreams){if(!n||typeof n!="object")throw new TypeError("Each entry of options.privateStreams must be an object.");if(!Number.isInteger(n.pid)||n.pid<16||n.pid>8190)throw new TypeError("A private stream's pid must be an integer between 0x0010 and 0x1ffe.");if(n.pid===e.scte35Pid||t.has(n.pid))throw new TypeError(`Private stream PID ${n.pid} is declared more than once.`);if(t.add(n.pid),n.streamType!==void 0&&(!Number.isInteger(n.streamType)||n.streamType<0||n.streamType>255))throw new TypeError("A private stream's streamType, when provided, must be a byte.");if(!Array.isArray(n.descriptors))throw new TypeError("A private stream's descriptors must be an array of Uint8Array.");let i=0;for(let a of n.descriptors){if(!(a instanceof Uint8Array)||a.byteLength<2)throw new TypeError("Each private stream descriptor must be a Uint8Array of at least two bytes.");if(a[1]!==a.byteLength-2)throw new TypeError("A private stream descriptor's length byte must equal its size minus two.");i+=a.byteLength}if(i>4095)throw new TypeError("A private stream's descriptors must fit in a 12-bit ES_info_length.")}}if(e.maxInterleaveDelta!==void 0&&!(e.maxInterleaveDelta>0))throw new TypeError("options.maxInterleaveDelta, when provided, must be a positive number.");if(e.onPacket!==void 0&&typeof e.onPacket!="function")throw new TypeError("options.onPacket, when provided, must be a function.");if(e.sampleAesEncryption!==void 0){let{key:t,iv:n}=e.sampleAesEncryption;if(!(t instanceof Uint8Array)||t.byteLength!==16)throw new TypeError("options.sampleAesEncryption.key must be a 16-byte Uint8Array.");if(!(n instanceof Uint8Array)||n.byteLength!==16)throw new TypeError("options.sampleAesEncryption.iv must be a 16-byte Uint8Array.")}super(),this._options=e}_createMuxer(e){return new Ea(e,this)}get _name(){return"MPEG-TS"}getSupportedTrackCounts(){return{video:{min:0,max:16},audio:{min:0,max:32},subtitle:{min:0,max:0},total:{min:0,max:48}}}get fileExtension(){return".ts"}get mimeType(){return"video/MP2T"}getSupportedCodecs(){return[...Te.filter(e=>["avc","hevc","mpeg2"].includes(e)),...Ee.filter(e=>["aac","mp3","mp2","ac3","eac3","dts"].includes(e))]}get supportsVideoTransformationMetadata(){return!1}get supportsTimestampedMediaData(){return!0}get negativeTimestampSupport(){return"prefer-non-negative"}},du=class extends nt{_createMuxer(e){return new Lf(e)}get _name(){return"WebVTT"}get fileExtension(){return Qk}get mimeType(){return lb}getSupportedCodecs(){return["webvtt"]}getSupportedTrackCounts(){return{video:{min:0,max:0},audio:{min:0,max:0},subtitle:{min:1,max:1},total:{min:1,max:1}}}get supportsVideoTransformationMetadata(){return!1}get supportsTimestampedMediaData(){return!0}get negativeTimestampSupport(){return"none"}},Kk=new du,mu=class extends nt{constructor(e){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(!(e.segmentFormat instanceof nt)&&(!Array.isArray(e.segmentFormat)||e.segmentFormat.length===0||!e.segmentFormat.every(t=>t instanceof nt)))throw new TypeError("options.segmentFormat must be an OutputFormat or a non-empty array of OutputFormat instances.");if(e.targetDuration!==void 0&&(typeof e.targetDuration!="number"||e.targetDuration<=0))throw new TypeError("options.targetDuration, when provided, must be a positive number.");if(e.nextSegmentBoundary!==void 0&&typeof e.nextSegmentBoundary!="function")throw new TypeError("options.nextSegmentBoundary, when provided, must be a function.");if(e.partDuration!==void 0&&(!Number.isFinite(e.partDuration)||e.partDuration<=0))throw new TypeError("options.partDuration, when provided, must be a positive finite number.");if(e.singleFilePerPlaylist!==void 0&&typeof e.singleFilePerPlaylist!="boolean")throw new TypeError("options.singleFilePerPlaylist, when provided, must be a boolean.");if(e.live!==void 0&&typeof e.live!="boolean")throw new TypeError("options.live, when provided, must be a boolean.");if(e.maxLiveSegmentCount!==void 0&&(typeof e.maxLiveSegmentCount!="number"||e.maxLiveSegmentCount<1||Number.isFinite(e.maxLiveSegmentCount)&&!Number.isInteger(e.maxLiveSegmentCount)))throw new TypeError("options.maxLiveSegmentCount, when provided, must be a positive integer or Infinity.");if(e.mediaTimestampBase!==void 0&&!Number.isFinite(e.mediaTimestampBase))throw new TypeError("options.mediaTimestampBase, when provided, must be a finite number.");if(e.getPlaylistPath!==void 0&&typeof e.getPlaylistPath!="function")throw new TypeError("options.getPlaylistPath, when provided, must be a function.");if(e.getSegmentPath!==void 0&&typeof e.getSegmentPath!="function")throw new TypeError("options.getSegmentPath, when provided, must be a function.");if(e.getInitPath!==void 0&&typeof e.getInitPath!="function")throw new TypeError("options.getInitPath, when provided, must be a function.");if(e.onMaster!==void 0&&typeof e.onMaster!="function")throw new TypeError("options.onMaster, when provided, must be a function.");if(e.onPlaylist!==void 0&&typeof e.onPlaylist!="function")throw new TypeError("options.onPlaylist, when provided, must be a function.");if(e.onSegment!==void 0&&typeof e.onSegment!="function")throw new TypeError("options.onSegment, when provided, must be a function.");if(e.onInit!==void 0&&typeof e.onInit!="function")throw new TypeError("options.onInit, when provided, must be a function.");if(e.onSegmentPopped!==void 0&&typeof e.onSegmentPopped!="function")throw new TypeError("options.onSegmentPopped, when provided, must be a function.");super(),this._options=e}_createMuxer(e){return new el(e,this._options,t=>[new cu(t,this._options)])}get _name(){return"HTTP Live Streaming (HLS)"}get fileExtension(){return".m3u8"}get mimeType(){return cr}getSupportedCodecs(){let e=new Set(ot(this._options.segmentFormat).flatMap(t=>t.getSupportedCodecs()));for(let t of lo)e.delete(t);return this._options.singleFilePerPlaylist?e.delete("webvtt"):e.add("webvtt"),[...e]}getSupportedTrackCounts(){let e=!1,t=!1;for(let n of ot(this._options.segmentFormat)){let i=n.getSupportedTrackCounts();e||=i.video.max>0,t||=i.audio.max>0}return{video:{min:0,max:e?1/0:0},audio:{min:0,max:t?1/0:0},subtitle:{min:0,max:1/0},total:{min:0,max:1/0}}}get supportsVideoTransformationMetadata(){return ot(this._options.segmentFormat).some(e=>e.supportsVideoTransformationMetadata)}get supportsTimestampedMediaData(){return!0}get negativeTimestampSupport(){let e=ot(this._options.segmentFormat);return e.some(t=>t.negativeTimestampSupport==="none")?"none":e.some(t=>t.negativeTimestampSupport==="prefer-non-negative")?"prefer-non-negative":e.some(t=>t.negativeTimestampSupport==="full")?"full":null}_codecUnsupportedHint(e){return e==="webvtt"&&this._options.singleFilePerPlaylist?" WebVTT segments are raw text and cannot be addressed via byte ranges, unlike the fragmented MP4 that carries 'ttml' subtitle tracks. Use 'ttml', or disable `singleFilePerPlaylist`.":" Using different segment formats may grant support for this codec."}},pR=["segmentFormat","targetDuration","partDuration","singleFilePerPlaylist","live","maxLiveSegmentCount","getPlaylistPath","getSegmentPath","getInitPath","separateRenditions"],hR=r=>r.some(e=>e.negativeTimestampSupport==="none")?"none":r.some(e=>e.negativeTimestampSupport==="prefer-non-negative")?"prefer-non-negative":r.some(e=>e.negativeTimestampSupport==="full")?"full":null,fu=class extends nt{constructor(e){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(typeof e.mpdPath!="string"||e.mpdPath.length===0)throw new TypeError("options.mpdPath must be a non-empty string.");if(e.onMpd!==void 0&&typeof e.onMpd!="function")throw new TypeError("options.onMpd, when provided, must be a function.");if(e.singleFilePerPlaylist){let t=ot(e.segmentFormat).find(n=>!(n instanceof Ca)&&!n._isFragmentedIsobmff());if(t)throw new TypeError(`options.singleFilePerPlaylist is not supported with ${t._name} segments: single-file DASH addresses each representation's initialization by byte range, which only CMAF or fragmented-MP4 segments write.`)}super(),this._options=e}_createMuxer(e){return new el(e,this._options,t=>[new lu(t,this._options)])}get _name(){return"MPEG-DASH"}get fileExtension(){return".mpd"}get mimeType(){return"application/dash+xml"}getSupportedCodecs(){let e=new Set(ot(this._options.segmentFormat).flatMap(t=>t.getSupportedCodecs()));return this._options.singleFilePerPlaylist?e.delete("webvtt"):e.add("webvtt"),[...e]}_codecUnsupportedHint(e){return e==="webvtt"&&this._options.singleFilePerPlaylist?" WebVTT segments are raw text and cannot be addressed via byte ranges, unlike the fragmented MP4 that carries 'ttml' subtitle tracks. Use 'ttml', or disable `singleFilePerPlaylist`.":""}getSupportedTrackCounts(){let e=!1,t=!1;for(let n of ot(this._options.segmentFormat)){let i=n.getSupportedTrackCounts();e||=i.video.max>0,t||=i.audio.max>0}return{video:{min:0,max:e?1/0:0},audio:{min:0,max:t?1/0:0},subtitle:{min:0,max:1/0},total:{min:1,max:1/0}}}get supportsVideoTransformationMetadata(){return ot(this._options.segmentFormat).some(e=>e.supportsVideoTransformationMetadata)}get supportsTimestampedMediaData(){return ot(this._options.segmentFormat).some(e=>e.supportsTimestampedMediaData)}get negativeTimestampSupport(){return hR(ot(this._options.segmentFormat))}},Gf=class extends nt{constructor(e){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(!Array.isArray(e.formats)||e.formats.length===0)throw new TypeError("options.formats must be a non-empty array.");let t=e.formats.filter(a=>a instanceof mu),n=e.formats.filter(a=>a instanceof fu);if(t.length!==1)throw new TypeError("options.formats must contain exactly one HlsOutputFormat instance (the underlying muxer uses the HLS master playlist as its root file).");if(t.length+n.length!==e.formats.length)throw new TypeError("options.formats may currently only contain HlsOutputFormat or DashOutputFormat instances.");let i=t[0];for(let a of n)for(let s of pR)if(i._options[s]!==a._options[s])throw new TypeError(`options.formats: composed formats must agree on '${s}' \u2014 pass the same value (or instance) to every format.`);super(),this._options=e,this._hlsFormat=i,this._dashFormats=n}_createMuxer(e){return new el(e,this._hlsFormat._options,t=>[new cu(t,this._hlsFormat._options),...this._dashFormats.map(n=>new lu(t,n._options))])}get _name(){return"Adaptive Streaming (HLS + DASH)"}get fileExtension(){return".m3u8"}get mimeType(){return this._hlsFormat.mimeType}getSupportedCodecs(){return this._hlsFormat.getSupportedCodecs()}_trackTypeUnsupportedHint(e){return this._hlsFormat._trackTypeUnsupportedHint(e)}getSupportedTrackCounts(){return this._hlsFormat.getSupportedTrackCounts()}get supportsVideoTransformationMetadata(){return this._hlsFormat.supportsVideoTransformationMetadata}get supportsTimestampedMediaData(){return this._hlsFormat.supportsTimestampedMediaData}get negativeTimestampSupport(){return this._hlsFormat.negativeTimestampSupport}_codecUnsupportedHint(e){return this._hlsFormat._codecUnsupportedHint(e)}};var $f=["video","audio","subtitle"],As=class r{constructor(e,t,n,i,a){this.id=e,this.output=t,this.type=n,this.source=i,this.metadata=a}isVideoTrack(){return this.type==="video"}isAudioTrack(){return this.type==="audio"}isSubtitleTrack(){return this.type==="subtitle"}canBePairedWith(e){if(!(e instanceof r))throw new TypeError("other must be an OutputTrack.");if(this===e)return!1;let t=ot(this.metadata.group),n=ot(e.metadata.group);for(let i of t)if(this.type!==e.type&&n.some(o=>i===o)||n.some(o=>i._pairedGroups.has(o)))return!0;return!1}},pu=class extends As{constructor(e,t,n,i){super(e,t,"video",n,i)}},hu=class extends As{constructor(e,t,n,i){super(e,t,"audio",n,i)}},gu=class extends As{constructor(e,t,n,i){super(e,t,"subtitle",n,i)}},Pt=class r{constructor(){this._pairedGroups=new Set}pairWith(e){if(!(e instanceof r))throw new TypeError("other must be an OutputTrackGroup.");if(this===e)throw new TypeError("Cannot pair a group with itself.");this._pairedGroups.add(e),e._pairedGroups.add(this)}},cb=r=>{if(!r||typeof r!="object")throw new TypeError("metadata must be an object.");if(r.languageCode!==void 0&&!mn(r.languageCode))throw new TypeError("metadata.languageCode, when provided, must be a three-letter, ISO 639-2/T language code.");if(r.name!==void 0&&typeof r.name!="string")throw new TypeError("metadata.name, when provided, must be a string.");if(r.disposition!==void 0&&Dy(r.disposition),r.maximumPacketCount!==void 0&&(!Number.isInteger(r.maximumPacketCount)||r.maximumPacketCount<0))throw new TypeError("metadata.maximumPacketCount, when provided, must be a non-negative integer.");if(r.bitrate!==void 0&&(!Number.isFinite(r.bitrate)||r.bitrate<0))throw new TypeError("metadata.bitrate, when provided, must be a non-negative number.");if(r.averageBitrate!==void 0&&(!Number.isFinite(r.averageBitrate)||r.averageBitrate<0))throw new TypeError("metadata.averageBitrate, when provided, must be a non-negative number.");if(r.group!==void 0&&!(r.group instanceof Pt)&&(!Array.isArray(r.group)||r.group.some(e=>!(e instanceof Pt))))throw new TypeError("metadata.group, when provided, must be an OutputTrackGroup instance or an array of OutputTrackGroup instances.")},pr=class extends Lt{constructor(t){super();this.state="pending";this.defaultTrackGroup=new Pt;this.tracks=[];this._onFinalize=null;this._unfinalizedTargets=new Set;this._rootWriterPromise=null;this._startPromise=null;this._cancelPromise=null;this._finalizePromise=null;this._mutex=new vt;this._metadataTags={};this._rootTarget=null;this._rootTargetPromise=null;this._firstMediaStreamTimestamp=null;if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(!(t.format instanceof nt))throw new TypeError("options.format must be an OutputFormat.");if(!(t.target instanceof rt||t.target instanceof Je))throw new TypeError("options.target must be a Target or a PathedTarget.");if(t.target instanceof rt&&this._rememberTarget(t.target),t.initTarget!==void 0&&!(t.initTarget instanceof rt)&&typeof t.initTarget!="function")throw new Error("options.initTarget, when provided, must be a Target or a function that returns or resolves to a Target.");if(t.onFinalize!==void 0&&typeof t.onFinalize!="function")throw new TypeError("options.onFinalize, when provided, must be a function.");this.format=t.format,this._target=t.target,this._onFinalize=t.onFinalize??null,this._initTarget=t.initTarget??null,this._initTarget instanceof rt&&this._rememberTarget(this._initTarget),this._muxer=t.format._createMuxer(this)}get target(){let t="Output.target cannot be used when using PathedTarget with an async callback. Use the 'target' event instead.";if(this._rootTargetPromise)throw new TypeError(t);let n=this._getRootTarget();if(M(n))throw new TypeError(t);return n}_getTargetValidated(t){b(this._target instanceof Je);let n=this._target.getTarget(t),i=a=>{if(!(a instanceof rt))throw new TypeError("getTarget must return a Target.");return a};return M(n)?n.then(i):i(n)}async _getTarget(t){b(this._target instanceof Je);let n=await this._getTargetValidated(t);return this._emit("target",{target:n,request:t,isRoot:t.isRoot}),this.state==="canceled"?await n._close():this._rememberTarget(n),n}_rememberTarget(t){this._unfinalizedTargets.add(t),t.on("finalized",()=>this._unfinalizedTargets.delete(t),{once:!0})}async _getInitTarget(){if(b(this._initTarget!==null),this._initTarget instanceof rt)return this._initTarget;let t=await this._initTarget();return this.state==="canceled"?await t._close():this._rememberTarget(t),t}_hasInitTarget(){return this._initTarget!==null}_getRootTarget(){if(this._rootTarget)return this._rootTarget;if(this._rootTargetPromise)return this._rootTargetPromise;if(this._target instanceof rt)return this._emit("target",{target:this._target,request:null,isRoot:!0}),this._rootTarget=this._target,this._target;let t={path:this._target.rootPath,isRoot:!0,mimeType:this.format.mimeType},n=this._getTargetValidated(t),i=a=>(this.state==="canceled"?a._close():this._rememberTarget(a),this._emit("target",{target:a,request:t,isRoot:!0}),this._rootTarget=a,a);return M(n)?this._rootTargetPromise=n.then(i):i(n)}_getRootWriter(t){return this._rootWriterPromise??=(async()=>{let n=await this._getRootTarget(),i=new Br(n,typeof t=="boolean"?t:t(n));return i.start(),i})()}addVideoTrack(t,n={}){if(!(t instanceof Nn))throw new TypeError("source must be a VideoSource.");if(cb(n),n.rotation!==void 0&&![0,90,180,270].includes(n.rotation))throw new TypeError(`Invalid video rotation: ${n.rotation}. Has to be 0, 90, 180 or 270.`);if(n.flip!==void 0&&typeof n.flip!="boolean")throw new TypeError("metadata.flip, when provided, must be a boolean.");if(n.transformationMatrix!==void 0&&(!Array.isArray(n.transformationMatrix)||n.transformationMatrix.length!==9||!n.transformationMatrix.every(a=>Number.isFinite(a))))throw new TypeError("metadata.transformationMatrix, when provided, must be an array of 9 finite numbers.");if(n.frameRate!==void 0&&(!Number.isFinite(n.frameRate)||n.frameRate<=0))throw new TypeError(`Invalid video frame rate: ${n.frameRate}. Must be a positive number.`);if(n.hasOnlyKeyPackets!==void 0&&typeof n.hasOnlyKeyPackets!="boolean")throw new TypeError("metadata.hasOnlyKeyPackets, when provided, must be a boolean.");if(n.canBeTransparent!==void 0&&typeof n.canBeTransparent!="boolean")throw new TypeError("metadata.canBeTransparent, when provided, must be a boolean.");if(n.decoderConfig!==void 0&&Vn({decoderConfig:n.decoderConfig},t._codec),n.primingPacket!==void 0){if(!(n.primingPacket instanceof oe))throw new TypeError("metadata.primingPacket, when provided, must be an EncodedPacket.");if(n.decoderConfig===void 0)throw new TypeError("metadata.primingPacket can only be provided alongside metadata.decoderConfig.")}if(n.parameterSets!==void 0&&!["inBand","outOfBand"].includes(n.parameterSets))throw new TypeError(`Invalid parameter set placement: ${n.parameterSets}. Must be 'inBand' or 'outOfBand'.`);if(n.dolbyVision!==void 0&&(Xu(n.dolbyVision,"metadata.dolbyVision"),t._codec!=="avc"&&t._codec!=="hevc"))throw new Error(`metadata.dolbyVision was provided, but ${t._codec} cannot carry a Dolby Vision configuration record. Dolby Vision rides on AVC or HEVC.`);if(n.closedCaptions!==void 0&&(Cw(n.closedCaptions,"metadata.closedCaptions"),t._codec!=="avc"&&t._codec!=="hevc"))throw new Error(`metadata.closedCaptions was provided, but ${t._codec} has no bitstream that can carry them. Closed captions ride in AVC or HEVC SEI messages.`);let i={...n};return i.group??=this.defaultTrackGroup,this._addTrack(new pu(this.tracks.length+1,this,t,i))}addAudioTrack(t,n={}){if(!(t instanceof Ln))throw new TypeError("source must be an AudioSource.");if(cb(n),n.decoderConfig!==void 0&&tt({decoderConfig:n.decoderConfig},t._codec),n.primingPacket!==void 0){if(!(n.primingPacket instanceof oe))throw new TypeError("metadata.primingPacket, when provided, must be an EncodedPacket.");if(n.decoderConfig===void 0)throw new TypeError("metadata.primingPacket can only be provided alongside metadata.decoderConfig.")}let i={...n};return i.group??=this.defaultTrackGroup,this._addTrack(new hu(this.tracks.length+1,this,t,i))}addSubtitleTrack(t,n={}){if(!(t instanceof wa))throw new TypeError("source must be a SubtitleSource.");cb(n);let i={...n};return i.group??=this.defaultTrackGroup,this._addTrack(new gu(this.tracks.length+1,this,t,i))}setMetadataTags(t){if(yl(t),this.state!=="pending")throw new Error("Cannot set metadata tags after output has been started or canceled.");this._metadataTags=t}_addTrack(t){if(this.state!=="pending")throw new Error("Cannot add track after output has been started or canceled.");if(t.source._connectedTrack)throw new Error("Source is already used for a track.");let n=this.format.getSupportedTrackCounts(),i=this.tracks.reduce((o,l)=>o+(l.type===t.type?1:0),0),a=n[t.type].max;if(i===a)throw new Error(a===0?`${this.format._name} does not support ${t.type} tracks.`+this.format._trackTypeUnsupportedHint(t.type):`${this.format._name} does not support more than ${a} ${t.type} track${a===1?"":"s"}.`);let s=n.total.max;if(this.tracks.length===s)throw new Error(`${this.format._name} does not support more than ${s} tracks${s===1?"":"s"} in total.`);if(t.isVideoTrack()){let o=this.format.getSupportedVideoCodecs();if(o.length===0)throw new Error(`${this.format._name} does not support video tracks.`+this.format._codecUnsupportedHint(t.source._codec));if(!o.includes(t.source._codec))throw new Error(`Codec '${t.source._codec}' cannot be contained within ${this.format._name}. Supported video codecs are: ${o.map(l=>`'${l}'`).join(", ")}.`+this.format._codecUnsupportedHint(t.source._codec))}else if(t.isAudioTrack()){let o=this.format.getSupportedAudioCodecs();if(o.length===0)throw new Error(`${this.format._name} does not support audio tracks.`+this.format._codecUnsupportedHint(t.source._codec));if(!o.includes(t.source._codec))throw new Error(`Codec '${t.source._codec}' cannot be contained within ${this.format._name}. Supported audio codecs are: ${o.map(l=>`'${l}'`).join(", ")}.`+this.format._codecUnsupportedHint(t.source._codec))}else if(t.isSubtitleTrack()){let o=this.format.getSupportedSubtitleCodecs();if(o.length===0)throw new Error(`${this.format._name} does not support subtitle tracks.`+this.format._codecUnsupportedHint(t.source._codec));if(!o.includes(t.source._codec))throw new Error(`Codec '${t.source._codec}' cannot be contained within ${this.format._name}. Supported subtitle codecs are: ${o.map(l=>`'${l}'`).join(", ")}.`+this.format._codecUnsupportedHint(t.source._codec))}return this.tracks.push(t),t.source._connectedTrack=t,t}hasEnoughTracks(){let t=this.format.getSupportedTrackCounts();for(let i of $f){let a=this.tracks.reduce((o,l)=>o+(l.type===i?1:0),0),s=t[i].min;if(a<s)return!1}let n=t.total.min;return!(this.tracks.length<n)}async start(){let t=this.format.getSupportedTrackCounts();for(let i of $f){let a=this.tracks.reduce((o,l)=>o+(l.type===i?1:0),0),s=t[i].min;if(a<s)throw new Error(s===t[i].max?`${this.format._name} requires exactly ${s} ${i} track${s===1?"":"s"}.`:`${this.format._name} requires at least ${s} ${i} track${s===1?"":"s"}.`)}let n=t.total.min;if(this.tracks.length<n)throw new Error(n===t.total.max?`${this.format._name} requires exactly ${n} track${n===1?"":"s"}.`:`${this.format._name} requires at least ${n} track${n===1?"":"s"}.`);if(this.state==="canceled")throw new Error("Output has been canceled.");return this._startPromise?(N._warn("Output has already been started."),this._startPromise):this._startPromise=(async()=>{this.state="started";let i=this._mutex.acquire();try{await this._muxer.start();let a=this.tracks.map(s=>s.source._start());await Promise.all(a)}finally{(await i)()}})()}getMimeType(){return this._muxer.getMimeType()}async cancel(){if(this.state==="canceled")return this._cancelPromise??void 0;if(this.state==="finalizing"||this.state==="finalized"){this.state==="finalized"&&N._warn("Output has already been finalized.");return}return this._cancelPromise=(async()=>{this.state="canceled";let t=await this._mutex.acquire();try{let n=this.tracks.map(i=>i.source._flushOrWaitForOngoingClose(!0));await Promise.all(n),await Promise.all([...this._unfinalizedTargets].map(i=>i._close())),this._unfinalizedTargets.clear()}finally{t()}})()}async finalize(){if(this.state==="pending")throw new Error("Cannot finalize before starting.");if(this.state==="canceled")throw new Error("Cannot finalize after canceling.");return this._finalizePromise?(N._warn("Output has already been finalized."),this._finalizePromise):this._finalizePromise=(async()=>{this.state="finalizing";let t=await this._mutex.acquire();try{let n=this.tracks.map(i=>i.source._flushOrWaitForOngoingClose(!1));if(await Promise.all(n),await this._muxer.finalize(),this._rootWriterPromise){let i=await this._rootWriterPromise;i.finalized||(await i.flush(),await i.finalize())}this._onFinalize&&await this._onFinalize(),this.state="finalized"}catch(n){throw this.state="canceled",n}finally{await Promise.all([...this._unfinalizedTargets].map(n=>n._close().catch(()=>{}))),this._unfinalizedTargets.clear(),t()}})()}};var Xf=r=>{if(!r||typeof r!="object")throw new TypeError("options.video, when provided, must be an object.");if(r?.discard!==void 0&&typeof r.discard!="boolean")throw new TypeError("options.video.discard, when provided, must be a boolean.");if(r?.forceTranscode!==void 0&&typeof r.forceTranscode!="boolean")throw new TypeError("options.video.forceTranscode, when provided, must be a boolean.");if(r?.codec!==void 0&&!Te.includes(r.codec))throw new TypeError(`options.video.codec, when provided, must be one of: ${Te.join(", ")}.`);let e=r?.bitrate;if(r?.quality!==void 0&&!(r.quality instanceof Pe))throw new TypeError("options.video.quality, when provided, must be a Quality.");if(r?.quality!==void 0&&e!==void 0)throw new TypeError("options.video.quality and options.video.bitrate cannot both be provided.");if(e!==void 0&&!(e instanceof Pe)&&(!Number.isInteger(e)||e<=0))throw new TypeError("options.video.bitrate, when provided, must be a positive integer or a quality.");if(r?.width!==void 0&&(!Number.isInteger(r.width)||r.width<=0))throw new TypeError("options.video.width, when provided, must be a positive integer.");if(r?.height!==void 0&&(!Number.isInteger(r.height)||r.height<=0))throw new TypeError("options.video.height, when provided, must be a positive integer.");if(r?.fit!==void 0&&!["fill","contain","cover"].includes(r.fit))throw new TypeError("options.video.fit, when provided, must be one of 'fill', 'contain', or 'cover'.");if(r?.width!==void 0&&r.height!==void 0&&r.fit===void 0)throw new TypeError("When both options.video.width and options.video.height are provided, options.video.fit must also be provided.");if(r?.rotate!==void 0&&![0,90,180,270].includes(r.rotate))throw new TypeError("options.video.rotate, when provided, must be 0, 90, 180 or 270.");if(r?.flip!==void 0&&typeof r.flip!="boolean")throw new TypeError("options.video.flip, when provided, must be a boolean.");if(r?.allowTransformationMetadata!==void 0&&typeof r.allowTransformationMetadata!="boolean")throw new TypeError("options.video.allowTransformationMetadata, when provided, must be a boolean.");if(r?.allowRotationMetadata!==void 0&&typeof r.allowRotationMetadata!="boolean")throw new TypeError("options.video.allowRotationMetadata, when provided, must be a boolean.");if(r?.crop!==void 0&&ga(r.crop,"options.video."),r?.frameRate!==void 0&&(!Number.isFinite(r.frameRate)||r.frameRate<=0))throw new TypeError("options.video.frameRate, when provided, must be a finite positive number.");if(r?.alpha!==void 0&&!["discard","keep"].includes(r.alpha))throw new TypeError("options.video.alpha, when provided, must be either 'discard' or 'keep'.");if(r?.keyFrameInterval!==void 0&&(!Number.isFinite(r.keyFrameInterval)||r.keyFrameInterval<0))throw new TypeError("options.video.keyFrameInterval, when provided, must be a non-negative number.");if(r?.parameterSets!==void 0&&!["inBand","outOfBand"].includes(r.parameterSets))throw new TypeError("options.video.parameterSets, when provided, must be 'inBand' or 'outOfBand'.");if(r?.bitDepth!==void 0&&!ba.includes(r.bitDepth))throw new TypeError(`options.video.bitDepth, when provided, must be one of ${ba.join(", ")}.`);if(r?.colorSpace!==void 0&&Wc(r.colorSpace,"options.video.colorSpace"),r?.dolbyVision!==void 0&&(Xu(r.dolbyVision,"options.video.dolbyVision"),r.dolbyVision.blSignalCompatibilityId===0))throw new Error("options.video.dolbyVision states a base layer that is not cross-compatible (blSignalCompatibilityId 0, profile 5), whose IPT-PQ-c2 base an encoder cannot produce.");if(r?.hdrStaticMetadata!==void 0&&Km(r.hdrStaticMetadata,"options.video.hdrStaticMetadata"),Xm(r?.bitDepth,r?.colorSpace,"options.video."),Qm(r?.hdrStaticMetadata,r?.colorSpace,"options.video."),r?.process!==void 0&&typeof r.process!="function")throw new TypeError("options.video.process, when provided, must be a function.");if(r?.preProcess!==void 0&&typeof r.preProcess!="function")throw new TypeError("options.video.preProcess, when provided, must be a function.");if(r?.preProcessFlush!==void 0&&typeof r.preProcessFlush!="function")throw new TypeError("options.video.preProcessFlush, when provided, must be a function.");if(r?.processFlush!==void 0&&typeof r.processFlush!="function")throw new TypeError("options.video.processFlush, when provided, must be a function.");if(r?.processedWidth!==void 0&&(!Number.isInteger(r.processedWidth)||r.processedWidth<=0))throw new TypeError("options.video.processedWidth, when provided, must be a positive integer.");if(r?.processedHeight!==void 0&&(!Number.isInteger(r.processedHeight)||r.processedHeight<=0))throw new TypeError("options.video.processedHeight, when provided, must be a positive integer.");if(r?.hardwareAcceleration!==void 0&&!["no-preference","prefer-hardware","prefer-software"].includes(r.hardwareAcceleration))throw new TypeError("options.video.hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.");if(r?.group!==void 0&&!(r.group instanceof Pt||Array.isArray(r.group)&&r.group.every(t=>t instanceof Pt)))throw new TypeError("options.video.group, when provided, must be an OutputTrackGroup or an array of OutputTrackGroups.");if(r?.maximumPacketCount!==void 0&&(!Number.isInteger(r.maximumPacketCount)||r.maximumPacketCount<0))throw new TypeError("options.video.maximumPacketCount, when provided, must be a non-negative integer.")},Kf=r=>{if(!r||typeof r!="object")throw new TypeError("options.audio, when provided, must be an object.");if(r?.discard!==void 0&&typeof r.discard!="boolean")throw new TypeError("options.audio.discard, when provided, must be a boolean.");if(r?.forceTranscode!==void 0&&typeof r.forceTranscode!="boolean")throw new TypeError("options.audio.forceTranscode, when provided, must be a boolean.");if(r?.codec!==void 0&&!Ee.includes(r.codec))throw new TypeError(`options.audio.codec, when provided, must be one of: ${Ee.join(", ")}.`);let e=r?.bitrate;if(r?.quality!==void 0&&!(r.quality instanceof Pe))throw new TypeError("options.audio.quality, when provided, must be a Quality.");if(r?.quality!==void 0&&e!==void 0)throw new TypeError("options.audio.quality and options.audio.bitrate cannot both be provided.");if(e!==void 0&&!(e instanceof Pe)&&(!Number.isInteger(e)||e<=0))throw new TypeError("options.audio.bitrate, when provided, must be a positive integer or a quality.");if(r?.numberOfChannels!==void 0&&(!Number.isInteger(r.numberOfChannels)||r.numberOfChannels<=0))throw new TypeError("options.audio.numberOfChannels, when provided, must be a positive integer.");if(r?.sampleRate!==void 0&&(!Number.isInteger(r.sampleRate)||r.sampleRate<=0))throw new TypeError("options.audio.sampleRate, when provided, must be a positive integer.");if(r?.sampleFormat!==void 0&&!["u8","s16","s32","f32"].includes(r.sampleFormat))throw new TypeError("options.audio.sampleFormat, when provided, must be one of: u8, s16, s32, f32.");if(r?.process!==void 0&&typeof r.process!="function")throw new TypeError("options.audio.process, when provided, must be a function.");if(r?.processedNumberOfChannels!==void 0&&(!Number.isInteger(r.processedNumberOfChannels)||r.processedNumberOfChannels<=0))throw new TypeError("options.audio.processedNumberOfChannels, when provided, must be a positive integer.");if(r?.processedSampleRate!==void 0&&(!Number.isInteger(r.processedSampleRate)||r.processedSampleRate<=0))throw new TypeError("options.audio.processedSampleRate, when provided, must be a positive integer.");if(r?.group!==void 0&&!(r.group instanceof Pt||Array.isArray(r.group)&&r.group.every(t=>t instanceof Pt)))throw new TypeError("options.audio.group, when provided, must be an OutputTrackGroup or an array of OutputTrackGroups.");if(r?.maximumPacketCount!==void 0&&(!Number.isInteger(r.maximumPacketCount)||r.maximumPacketCount<0))throw new TypeError("options.audio.maximumPacketCount, when provided, must be a non-negative integer.")},Qf=r=>{if(!r||typeof r!="object")throw new TypeError("options.subtitle, when provided, must be an object.");if(r?.discard!==void 0&&typeof r.discard!="boolean")throw new TypeError("options.subtitle.discard, when provided, must be a boolean.");if(r?.codec!==void 0&&!Mt.includes(r.codec))throw new TypeError(`options.subtitle.codec, when provided, must be one of: ${Mt.join(", ")}.`);if(r?.group!==void 0&&!(r.group instanceof Pt||Array.isArray(r.group)&&r.group.every(e=>e instanceof Pt)))throw new TypeError("options.subtitle.group, when provided, must be an OutputTrackGroup or an array of OutputTrackGroups.")},ub=2,db=48e3,jk=256,rl=class r{constructor(e){this._state="idle";this._timestampOffset=0;this._timestampOffsetAdjusted=!1;this._copyTimestampPossible=new Map;this._copyStartPackets=new Map;this._trackDurations=new Map;this._nextOutputTrackId=0;this._outputTrackIds=[];this._outputOwnTrackGroups=[];this._trackPumps=[];this._composable=!1;this._executed=!1;this._executionUntil=1/0;this._finishRequested=!1;this._pauseRequested=!1;this._synchronizer=new mb(this);this._totalDuration=null;this._maxTimestamps=new Map;this.onProgress=void 0;this._computeProgress=!1;this._lastProgress=0;this._undecodableSourceCodecs=[];this.isValid=!1;this.utilizedTracks=[];this.discardedTracks=[];if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(!(e.input instanceof _n))throw new TypeError("options.input must be an Input.");if(!(e.output instanceof pr))throw new TypeError("options.output must be an Output.");if(e.tracks!==void 0&&e.tracks!=="all"&&e.tracks!=="primary")throw new TypeError("options.tracks, when provided, must be either 'all' or 'primary'.");if(e.composable!==void 0&&typeof e.composable!="boolean")throw new TypeError("options.composable, when provided, must be a boolean.");if(e.copy!==void 0&&e.copy!==!1){if(!e.copy||typeof e.copy!="object")throw new TypeError("options.copy, when provided, must be an object or false.");if(e.copy.mode!==void 0&&!["forced","preferred"].includes(e.copy.mode))throw new TypeError("options.copy.mode, when provided, must be 'forced' or 'preferred'.");if(e.copy.shiftTolerance!==void 0&&(!Ve(e.copy.shiftTolerance)||e.copy.shiftTolerance<0))throw new TypeError("options.copy.shiftTolerance, when provided, must be a non-negative number.");if(e.copy.boundaryPolicy!==void 0&&!["expand","shrink"].includes(e.copy.boundaryPolicy))throw new TypeError("options.copy.boundaryPolicy, when provided, must be 'expand' or 'shrink'.");if(e.copy.boundaryTolerance!==void 0&&(!Ve(e.copy.boundaryTolerance)||e.copy.boundaryTolerance<0))throw new TypeError("options.copy.boundaryTolerance, when provided, must be a non-negative number.")}let t=e.composable??!1;if(t){if(e.tags!==void 0)throw new TypeError("options.tags cannot be set by a composable conversion; set metadata directly on the output instead.");if(e.output.state!=="pending")throw new TypeError("options.output must not have been started yet.")}else if(e.output.tracks.length>0||Object.keys(e.output._metadataTags).length>0||e.output.state!=="pending")throw new TypeError("options.output must be fresh: no tracks or metadata tags added and not started.");if(e.video!==void 0&&typeof e.video!="function")if(Array.isArray(e.video))for(let n of e.video)Xf(n);else Xf(e.video);if(e.audio!==void 0&&typeof e.audio!="function")if(Array.isArray(e.audio))for(let n of e.audio)Kf(n);else Kf(e.audio);if(e.subtitle!==void 0&&typeof e.subtitle!="function")if(Array.isArray(e.subtitle))for(let n of e.subtitle)Qf(n);else Qf(e.subtitle);if(e.trim!==void 0&&(!e.trim||typeof e.trim!="object"))throw new TypeError("options.trim, when provided, must be an object.");if(e.trim?.start!==void 0&&!Number.isFinite(e.trim.start))throw new TypeError("options.trim.start, when provided, must be a finite number.");if(e.trim?.end!==void 0&&!Ve(e.trim.end))throw new TypeError("options.trim.end, when provided, must be a number.");if(e.trim?.start!==void 0&&e.trim.end!==void 0&&e.trim.start>=e.trim.end)throw new TypeError("options.trim.start must be less than options.trim.end.");if(e.tags!==void 0&&(typeof e.tags!="object"||!e.tags)&&typeof e.tags!="function")throw new TypeError("options.tags, when provided, must be an object or a function.");if(typeof e.tags=="object"&&yl(e.tags),e.showWarnings!==void 0&&typeof e.showWarnings!="boolean")throw new TypeError("options.showWarnings, when provided, must be a boolean.");this._options=e,this._copyMode=e.copy===!1?!1:e.copy?.mode??"preferred",this._copyTimestampShiftTolerance=e.copy===!1?0:e.copy?.shiftTolerance??0,this._copyBoundaryPolicy=e.copy===!1?"expand":e.copy?.boundaryPolicy??"expand",this._copyBoundaryTolerance=e.copy===!1?1/0:e.copy?.boundaryTolerance??1/0,this._composable=t,this.input=e.input,this.output=e.output}get state(){return this._state}static async init(e){let t=new r(e);return await t._init(),t}async _init(){let e=await this.input.getFormat(),t,n=this._options.tracks;if(n===void 0&&(n=e.name.includes("(HLS)")?"primary":"all"),n==="all")t=await this.input.getTracks();else if(n==="primary"){let u=await this.input.getPrimaryVideoTrack(),d=await this.input.getPrimaryAudioTrack();t=[u,d].filter(m=>m!==null);for(let m of await this.input.getSubtitleTracks())this.discardedTracks.push({track:m,reason:"not_a_primary_track",trackOptions:{}})}else be(n),b(!1);let i=this.output.format.getSupportedTrackCounts(),a=1,s=1,o=1,l=[],c=[];for(let u of t){let d;if(u.isVideoTrack())if(this._options.video)if(typeof this._options.video=="function"){let p=await this._options.video(u,a)??{};if(Array.isArray(p))for(let g of p)Xf(g);else Xf(p);d=Array.isArray(p)?p:[p],a++}else d=Array.isArray(this._options.video)?this._options.video:[this._options.video];else d=[{}];else if(u.isAudioTrack())if(this._options.audio)if(typeof this._options.audio=="function"){let p=await this._options.audio(u,s)??{};if(Array.isArray(p))for(let g of p)Kf(g);else Kf(p);d=Array.isArray(p)?p:[p],s++}else d=Array.isArray(this._options.audio)?this._options.audio:[this._options.audio];else d=[{}];else if(u.isSubtitleTrack())if(this._options.subtitle)if(typeof this._options.subtitle=="function"){let p=await this._options.subtitle(u,o)??{};if(Array.isArray(p))for(let g of p)Qf(g);else Qf(p);d=Array.isArray(p)?p:[p],o++}else d=Array.isArray(this._options.subtitle)?this._options.subtitle:[this._options.subtitle];else d=[{}];else b(!1);let m=d.filter(p=>p.discard);for(let p of m)this.discardedTracks.push({track:u,reason:"discarded_by_user",trackOptions:p});if(d.length===m.length){d.length===0&&this.discardedTracks.push({track:u,reason:"discarded_by_user",trackOptions:{}});continue}let f=d.filter(p=>!p.discard);l.push(u),c.push(f)}this._options.trim?.start!==void 0?this._startTimestamp=this._options.trim.start:this._startTimestamp=Math.max(await this.input.getFirstTimestamp(l),0),this._endTimestamp=Math.max(this._options.trim?.end??1/0,this._startTimestamp),this._timestampOffset=-this._startTimestamp;for(let u=0;u<l.length;u++){let d=l[u],m=c[u];for(let f of m){if(this.output.tracks.length===i.total.max){this.discardedTracks.push({track:d,reason:"max_track_count_reached",trackOptions:f});continue}if(this.output.tracks.reduce((h,y)=>h+(y.type===d.type?1:0),0)===i[d.type].max){this.discardedTracks.push({track:d,reason:"max_track_count_of_type_reached",trackOptions:f});continue}let g=this._nextOutputTrackId++;d.isVideoTrack()?await this._processVideoTrack(d,f,g):d.isAudioTrack()?await this._processAudioTrack(d,f,g):d.isSubtitleTrack()?await this._processSubtitleTrack(d,f,g):b(!1)}}for(let u=0;u<this.utilizedTracks.length-1;u++)for(let d=u+1;d<this.utilizedTracks.length;d++){let m=this.utilizedTracks[u],f=this.utilizedTracks[d],p=this._outputOwnTrackGroups[u],g=this._outputOwnTrackGroups[d];b(p!==void 0),b(g!==void 0),p&&g&&m.canBePairedWith(f)&&p.pairWith(g)}if(!this._composable){let u={...await this.input.getMetadataTags()};delete u.creationTime;let d;if(this._options.tags){let p=typeof this._options.tags=="function"?await this._options.tags(u):this._options.tags;yl(p),d=p}else d=u;let m=e.mimeType===this.output.format.mimeType;u.raw===d.raw&&!m&&delete d.raw,this.output.setMetadataTags(d)}if(this._composable?this.isValid=!0:this.isValid=this.output.hasEnoughTracks()&&this.output.tracks.length>0,this._options.showWarnings??!0){let u=[],d=this.discardedTracks.filter(m=>m.reason!=="discarded_by_user");d.length>0&&(u.push("Some tracks had to be discarded from the conversion:",d),_y()&&d.some(m=>m.reason==="undecodable_source_codec")&&u.push(`
|
|
77
77
|
|
|
78
78
|
More than one copy of Mediabunny is loaded, which is the usual cause of this: an extension package such as @ahmedrowaihi/mediabunny-server registers its codecs on the copy it imported, and this conversion is holding the other one, so those codecs look absent. Install the core under the name the extensions import it by: npm i "mediabunny@npm:@ahmedrowaihi/mediabunny@<version>".`)),this.isValid||(u.length>0&&u.push(`
|
|
79
79
|
|