mirror of
https://github.com/arcodange-org/mediabunny.git
synced 2026-10-03 13:53:53 +02:00
3 lines
28 KiB
JavaScript
3 lines
28 KiB
JavaScript
"use strict";var Metamuxer=(()=>{var re=Object.defineProperty;var xe=Object.getOwnPropertyDescriptor;var ye=Object.getOwnPropertyNames;var ke=Object.prototype.hasOwnProperty;var Se=(t,r)=>{for(var e in r)re(t,e,{get:r[e],enumerable:!0})},we=(t,r,e,s)=>{if(r&&typeof r=="object"||typeof r=="function")for(let o of ye(r))!ke.call(t,o)&&o!==e&&re(t,o,{get:()=>r[o],enumerable:!(s=xe(r,o))||s.enumerable});return t};var ve=t=>we(re({},"__esModule",{value:!0}),t);var gt={};Se(gt,{ArrayBufferTarget:()=>ee,AudioBufferSource:()=>$,AudioDataSource:()=>R,CanvasSource:()=>W,FileSystemWritableFileStreamTarget:()=>te,MediaStreamAudioTrackSource:()=>H,MediaStreamVideoTrackSource:()=>D,Mp4OutputFormat:()=>G,Output:()=>Q,StreamTarget:()=>I,Target:()=>O,VideoFrameSource:()=>_});var le=(t,r,e)=>{if(t==="avc"){let s=100;r<=768&&e<=432?s=66:r<=1920&&e<=1080&&(s=77);let o=0,i=r>1920||e>1080?50:41,a=s.toString(16).padStart(2,"0"),l=o.toString(16).padStart(2,"0"),u=i.toString(16).padStart(2,"0");return`avc1.${a}${l}${u}`}else if(t==="hevc"){let s=0,o=1,i=Array(32).fill(0);i[o]=1;let a=parseInt(i.reverse().join(""),2).toString(16).replace(/^0+/,""),l="L",u=120;return r<=1280&&e<=720?u=93:r<=1920&&e<=1080?u=120:r<=3840&&e<=2160?u=150:(l="H",u=180),`hev1.${s===0?"":String.fromCharCode(65+s-1)}${o}.${a}.${l}${u}.B0`}else{if(t==="vp8")return"vp8";if(t==="vp9"){let s="00",o;return r<=854&&e<=480?o="21":r<=1280&&e<=720?o="31":r<=1920&&e<=1080?o="41":r<=3840&&e<=2160?o="51":o="61",`vp09.${s}.${o}.08`}else if(t==="av1"){let o;return r<=854&&e<=480?o="01":r<=1280&&e<=720?o="03":r<=1920&&e<=1080?o="04":r<=3840&&e<=2160?o="07":o="09",`av01.0.${o}M.08`}}throw new Error(`Unhandled codec '${t}'.`)},de=(t,r,e)=>{if(t==="aac")return r>=2&&e<=24e3?"mp4a.40.29":e<=24e3?"mp4a.40.5":"mp4a.40.2";if(t==="opus")return"opus";if(t==="vorbis")return"vorbis";throw new Error(`Unhandled codec '${t}'.`)};function c(t){if(!t)throw new Error("Assertion failed.")}var z=t=>t&&t[t.length-1],w=t=>t>=0&&t<2**32;var v=class{constructor(r,e){this.connectedTrack=null;this.codec=r,this.metadata=e}ensureNotFinalizing(){if(this.connectedTrack?.output.finalizing)throw new Error("Cannot call digest after output has started finalizing.")}start(){}async flush(){}},M=class{constructor(r,e){this.connectedTrack=null;this.codec=r,this.metadata=e}ensureNotFinalizing(){if(this.connectedTrack?.output.finalizing)throw new Error("Cannot call digest after output has started finalizing.")}start(){}async flush(){}};var Ae=5,V=class{constructor(r,e){this.source=r;this.codecConfig=e;this.encoder=null;this.lastMultipleOfKeyFrameInterval=-1}digest(r){this.source.ensureNotFinalizing(),this.ensureEncoder(r),c(this.encoder);let e=Math.floor(r.timestamp/1e6/Ae);this.encoder.encode(r,{keyFrame:e!==this.lastMultipleOfKeyFrameInterval}),this.lastMultipleOfKeyFrameInterval=e}ensureEncoder(r){this.encoder||(this.encoder=new VideoEncoder({output:(e,s)=>this.source.connectedTrack?.output.muxer.addEncodedVideoChunk(this.source.connectedTrack,e,s),error:e=>console.error(e)}),this.encoder.configure({codec:le(this.codecConfig.codec,r.codedWidth,r.codedHeight),width:r.codedWidth,height:r.codedHeight,bitrate:this.codecConfig.bitrate}))}async flush(){return this.encoder?.flush()}},_=class extends v{constructor(r,e={}){super(r.codec,e),this.encoder=new V(this,r)}digest(r){this.encoder.digest(r)}flush(){return this.encoder.flush()}},W=class extends v{constructor(e,s,o={}){super(s.codec,o);this.canvas=e;this.encoder=new V(this,s)}digest(e,s=0){let o=new VideoFrame(this.canvas,{timestamp:Math.round(1e6*e),duration:Math.round(1e6*s)});this.encoder.digest(o),o.close()}flush(){return this.encoder.flush()}},D=class extends v{constructor(e,s,o={}){super(s.codec,o);this.track=e;this.abortController=null;this.encoder=new V(this,s)}start(){this.abortController=new AbortController;let e=new MediaStreamTrackProcessor({track:this.track}),s=new WritableStream({write:o=>{this.encoder.digest(o),o.close()}});e.readable.pipeTo(s,{signal:this.abortController.signal}).catch(o=>{o instanceof DOMException&&o.name==="AbortError"||console.error("Pipe error:",o)})}async flush(){this.abortController&&(this.abortController.abort(),this.abortController=null),await this.encoder.flush()}};var B=class{constructor(r,e){this.source=r;this.codecConfig=e;this.encoder=null}digest(r){this.source.ensureNotFinalizing(),this.ensureEncoder(r),c(this.encoder),this.encoder.encode(r)}ensureEncoder(r){this.encoder||(this.encoder=new AudioEncoder({output:(e,s)=>this.source.connectedTrack?.output.muxer.addEncodedAudioChunk(this.source.connectedTrack,e,s),error:e=>console.error(e)}),this.encoder.configure({codec:de(this.codecConfig.codec,r.numberOfChannels,r.sampleRate),numberOfChannels:r.numberOfChannels,sampleRate:r.sampleRate,bitrate:this.codecConfig.bitrate}))}async flush(){return this.encoder?.flush()}},R=class extends M{constructor(r,e={}){super(r.codec,e),this.encoder=new B(this,r)}digest(r){this.encoder.digest(r)}flush(){return this.encoder.flush()}},$=class extends M{constructor(e,s={}){super(e.codec,s);this.accumulatedFrameCount=0;this.encoder=new B(this,e)}digest(e){let s=e.numberOfChannels,o=e.sampleRate,i=e.length,a=new Float32Array(s*i);for(let u=0;u<s;u++){let f=e.getChannelData(u);a.set(f,u*i)}let l=new AudioData({format:"f32-planar",sampleRate:o,numberOfFrames:i,numberOfChannels:s,timestamp:Math.round(1e6*this.accumulatedFrameCount/o),data:a});this.encoder.digest(l),l.close(),this.accumulatedFrameCount+=i}flush(){return this.encoder.flush()}},H=class extends M{constructor(e,s,o={}){super(s.codec,o);this.track=e;this.abortController=null;this.encoder=new B(this,s)}start(){this.abortController=new AbortController;let e=new MediaStreamTrackProcessor({track:this.track}),s=new WritableStream({write:o=>{this.encoder.digest(o),o.close()}});e.readable.pipeTo(s,{signal:this.abortController.signal}).catch(o=>{o instanceof DOMException&&o.name==="AbortError"||console.error("Pipe error:",o)})}async flush(){this.abortController&&(this.abortController.abort(),this.abortController=null),await this.encoder.flush()}};var Q=class{constructor(r){this.tracks=[];this.started=!1;this.finalizing=!1;this.writer=r.target.createWriter(),this.muxer=r.format.createMuxer(this)}addTrack(r){if(this.started)throw new Error("Cannot add track after output has started.");if(r.connectedTrack)throw new Error("Source is already used for a track.");let e={id:this.tracks.length+1,output:this,type:r instanceof v?"video":"audio",source:r};this.tracks.push(e),r.connectedTrack=e}start(){if(this.started)throw new Error("Output already started.");this.started=!0,this.muxer.start();for(let r of this.tracks)r.source.start()}async finalize(){if(this.finalizing)throw new Error("Cannot call finalize twice.");this.finalizing=!0;let r=this.tracks.map(e=>e.source.flush());await Promise.all(r),this.muxer.finalize(),this.writer.flush(),this.writer.finalize()}};var d=new Uint8Array(8),x=new DataView(d.buffer),b=t=>[(t%256+256)%256],m=t=>(x.setUint16(0,t,!1),[d[0],d[1]]),Oe=t=>(x.setInt16(0,t,!1),[d[0],d[1]]),fe=t=>(x.setUint32(0,t,!1),[d[1],d[2],d[3]]),n=t=>(x.setUint32(0,t,!1),[d[0],d[1],d[2],d[3]]),ze=t=>(x.setInt32(0,t,!1),[d[0],d[1],d[2],d[3]]),A=t=>(x.setUint32(0,Math.floor(t/2**32),!1),x.setUint32(4,t,!1),[d[0],d[1],d[2],d[3],d[4],d[5],d[6],d[7]]),oe=t=>(x.setInt16(0,2**8*t,!1),[d[0],d[1]]),g=t=>(x.setInt32(0,2**16*t,!1),[d[0],d[1],d[2],d[3]]),se=t=>(x.setInt32(0,2**30*t,!1),[d[0],d[1],d[2],d[3]]),C=(t,r=!1)=>{let e=Array(t.length).fill(null).map((s,o)=>t.charCodeAt(o));return r&&e.push(0),e},ie=t=>{let r=null;for(let e of t)(!r||e.presentationTimestamp>r.presentationTimestamp)&&(r=e);return r},me=t=>{let r=t*(Math.PI/180),e=Math.cos(r),s=Math.sin(r);return[e,s,0,-s,e,0,0,0,1]},he=me(0),pe=t=>[g(t[0]),g(t[1]),se(t[2]),g(t[3]),g(t[4]),se(t[5]),g(t[6]),g(t[7]),se(t[8])],p=(t,r,e)=>({type:t,contents:r&&new Uint8Array(r.flat(10)),children:e}),h=(t,r,e,s,o)=>p(t,[b(r),fe(e),s??[]],o),be=t=>{let r=512;return t.fragmented?p("ftyp",[C("iso5"),n(r),C("iso5"),C("iso6"),C("mp41")]):p("ftyp",[C("isom"),n(r),C("isom"),t.holdsAvc?C("avc1"):[],C("mp41")])},q=t=>({type:"mdat",largeSize:t}),Ce=t=>({type:"free",size:t}),U=(t,r,e=!1)=>p("moov",void 0,[Ie(r,t),...t.map(s=>Ee(s,r)),e?rt(t):null]),Ie=(t,r)=>{let e=T(Math.max(0,...r.filter(a=>a.samples.length>0).map(a=>{let l=ie(a.samples);return l.presentationTimestamp+l.duration})),j),s=Math.max(...r.map(a=>a.track.id))+1,o=!w(t)||!w(e),i=o?A:n;return h("mvhd",+o,0,[i(t),i(t),n(j),i(e),g(1),oe(1),Array(10).fill(0),pe(he),Array(24).fill(0),n(s)])},Ee=(t,r)=>p("trak",void 0,[Me(t,r),Ve(t,r)]),Me=(t,r)=>{let e=ie(t.samples),s=T(e?e.presentationTimestamp+e.duration:0,j),o=!w(r)||!w(s),i=o?A:n,a;if(t.type==="video"){let l=t.track.source.metadata.rotation;a=l===void 0||typeof l=="number"?me(l??0):l}else a=he;return h("tkhd",+o,3,[i(r),i(r),n(t.track.id),n(0),i(s),Array(8).fill(0),m(0),m(0),oe(t.type==="audio"?1:0),m(0),pe(a),g(t.type==="video"?t.info.width:0),g(t.type==="video"?t.info.height:0)])},Ve=(t,r)=>p("mdia",void 0,[Be(t,r),Ue(t.type==="video"?"vide":"soun"),Fe(t)]),Be=(t,r)=>{let e=ie(t.samples),s=T(e?e.presentationTimestamp+e.duration:0,t.timescale),o=!w(r)||!w(s),i=o?A:n;return h("mdhd",+o,0,[i(r),i(r),n(t.timescale),i(s),m(21956),m(0)])},Ue=t=>h("hdlr",0,0,[C("mhlr"),C(t),n(0),n(0),n(0),C("mp4-muxer-hdlr",!0)]),Fe=t=>p("minf",void 0,[t.type==="video"?Pe():Ne(),Le(),De(t)]),Pe=()=>h("vmhd",0,1,[m(0),m(0),m(0),m(0)]),Ne=()=>h("smhd",0,0,[m(0),m(0)]),Le=()=>p("dinf",void 0,[_e()]),_e=()=>h("dref",0,0,[n(1)],[We()]),We=()=>h("url ",0,1),De=t=>{let r=t.compositionTimeOffsetTable.length>1||t.compositionTimeOffsetTable.some(e=>e.sampleCompositionTimeOffset!==0);return p("stbl",void 0,[Re(t),Ge(t),Ye(t),Ze(t),Je(t),et(t),r?tt(t):null])},Re=t=>h("stsd",0,0,[n(1)],[t.type==="video"?$e(ct[t.track.source.codec],t):qe(mt[t.track.source.codec],t)]),$e=(t,r)=>p(t,[Array(6).fill(0),m(1),m(0),m(0),Array(12).fill(0),m(r.info.width),m(r.info.height),n(4718592),n(4718592),n(0),m(1),Array(32).fill(0),m(24),Oe(65535)],[ft[r.track.source.codec](r)]),He=t=>t.info.decoderConfig&&p("avcC",[...new Uint8Array(t.info.decoderConfig.description)]),Qe=t=>t.info.decoderConfig&&p("hvcC",[...new Uint8Array(t.info.decoderConfig.description)]),ce=t=>{if(!t.info.decoderConfig)return null;let r=t.info.decoderConfig;if(!r.colorSpace)throw new Error("'colorSpace' is required in the decoder config for VP8/VP9.");let e=r.codec.split("."),s=Number(e[1]),o=Number(e[2]),l=(Number(e[3])<<4)+(0<<1)+Number(r.colorSpace.fullRange);return h("vpcC",1,0,[b(s),b(o),b(l),b(2),b(2),b(2),m(0)])},je=()=>{let e=(1<<7)+1;return p("av1C",[e,0,0,0])},qe=(t,r)=>p(t,[Array(6).fill(0),m(1),m(0),m(0),n(0),m(r.info.numberOfChannels),m(16),m(0),m(0),g(r.info.sampleRate)],[ht[r.track.source.codec](r)]),Ke=t=>{let r=new Uint8Array(t.info.decoderConfig.description);return h("esds",0,0,[n(58753152),b(32+r.byteLength),m(1),b(0),n(75530368),b(18+r.byteLength),b(64),b(21),fe(0),n(130071),n(130071),n(92307584),b(r.byteLength),...r,n(109084800),b(1),b(2)])},Xe=t=>{let r=3840,e=0,s=t.info.decoderConfig?.description;if(s){if(s.byteLength<18)throw new TypeError("Invalid decoder description provided for Opus; must be at least 18 bytes long.");let o=ArrayBuffer.isView(s)?new DataView(s.buffer,s.byteOffset,s.byteLength):new DataView(s);r=o.getUint16(10,!0),e=o.getInt16(14,!0)}return p("dOps",[b(0),b(t.info.numberOfChannels),m(r),n(t.info.sampleRate),oe(e),b(0)])},Ge=t=>h("stts",0,0,[n(t.timeToSampleTable.length),t.timeToSampleTable.map(r=>[n(r.sampleCount),n(r.sampleDelta)])]),Ye=t=>{if(t.samples.every(e=>e.type==="key"))return null;let r=[...t.samples.entries()].filter(([,e])=>e.type==="key");return h("stss",0,0,[n(r.length),r.map(([e])=>n(e+1))])},Ze=t=>h("stsc",0,0,[n(t.compactlyCodedChunkTable.length),t.compactlyCodedChunkTable.map(r=>[n(r.firstChunk),n(r.samplesPerChunk),n(1)])]),Je=t=>h("stsz",0,0,[n(0),n(t.samples.length),t.samples.map(r=>n(r.size))]),et=t=>t.finalizedChunks.length>0&&z(t.finalizedChunks).offset>=2**32?h("co64",0,0,[n(t.finalizedChunks.length),t.finalizedChunks.map(r=>A(r.offset))]):h("stco",0,0,[n(t.finalizedChunks.length),t.finalizedChunks.map(r=>n(r.offset))]),tt=t=>h("ctts",0,0,[n(t.compositionTimeOffsetTable.length),t.compositionTimeOffsetTable.map(r=>[n(r.sampleCount),n(r.sampleCompositionTimeOffset)])]),rt=t=>p("mvex",void 0,t.map(st)),st=t=>h("trex",0,0,[n(t.track.id),n(1),n(0),n(0),n(0)]),ne=(t,r)=>p("moof",void 0,[ot(t),...r.map(it)]),ot=t=>h("mfhd",0,0,[n(t)]),Te=t=>{let r=0,e=0,s=0,o=0,i=t.type==="delta";return e|=+i,i?r|=1:r|=2,r<<24|e<<16|s<<8|o},it=t=>p("traf",void 0,[nt(t),at(t),ut(t)]),nt=t=>{c(t.currentChunk);let r=0;r|=8,r|=16,r|=32,r|=131072;let e=t.currentChunk.samples[1]??t.currentChunk.samples[0],s={duration:e.timescaleUnitsToNextSample,size:e.size,flags:Te(e)};return h("tfhd",0,r,[n(t.track.id),n(s.duration),n(s.size),n(s.flags)])},at=t=>(c(t.currentChunk),h("tfdt",1,0,[A(T(t.currentChunk.startTimestamp,t.timescale))])),ut=t=>{c(t.currentChunk);let r=t.currentChunk.samples.map(k=>k.timescaleUnitsToNextSample),e=t.currentChunk.samples.map(k=>k.size),s=t.currentChunk.samples.map(Te),o=t.currentChunk.samples.map(k=>T(k.presentationTimestamp-k.decodeTimestamp,t.timescale)),i=new Set(r),a=new Set(e),l=new Set(s),u=new Set(o),f=l.size===2&&s[0]!==s[1],y=i.size>1,E=a.size>1,N=!f&&l.size>1,ue=u.size>1||[...u].some(k=>k!==0),S=0;return S|=1,S|=4*+f,S|=256*+y,S|=512*+E,S|=1024*+N,S|=2048*+ue,h("trun",1,S,[n(t.currentChunk.samples.length),n(t.currentChunk.offset-t.currentChunk.moofOffset||0),f?n(s[0]):[],t.currentChunk.samples.map((k,L)=>[y?n(r[L]):[],E?n(e[L]):[],N?n(s[L]):[],ue?ze(o[L]):[]])])},ge=t=>p("mfra",void 0,[...t.map(lt),dt()]),lt=(t,r)=>h("tfra",1,0,[n(t.track.id),n(63),n(t.finalizedChunks.length),t.finalizedChunks.map(s=>[A(T(s.startTimestamp,t.timescale)),A(s.moofOffset),n(r+1),n(1),n(1)])]),dt=()=>h("mfro",0,0,[n(0)]),ct={avc:"avc1",hevc:"hvc1",vp8:"vp08",vp9:"vp09",av1:"av01"},ft={avc:He,hevc:Qe,vp8:ce,vp9:ce,av1:je},mt={aac:"mp4a",opus:"Opus"},ht={aac:Ke,opus:Xe};var K=class{constructor(r){this.output=r}};var j=1e3,pt=2082844800,T=(t,r,e=!0)=>{let s=t*r;return e?Math.round(s):s},X=class extends K{constructor(e,s){super(e);this.#r=new Uint8Array(8);this.#o=new DataView(this.#r.buffer);this.offsets=new WeakMap;this.#n=null;this.#i=null;this.#s=[];this.#a=Math.floor(Date.now()/1e3)+pt;this.#u=[];this.#h=1;this.#e=e.writer,this.#t=s}#e;#t;#r;#o;#n;#i;#s;#a;#u;#h;writeU32(e){this.#o.setUint32(0,e,!1),this.#e.write(this.#r.subarray(0,4))}writeU64(e){this.#o.setUint32(0,Math.floor(e/2**32),!1),this.#o.setUint32(4,e,!1),this.#e.write(this.#r.subarray(0,8))}writeAscii(e){for(let s=0;s<e.length;s++)this.#o.setUint8(s%8,e.charCodeAt(s)),s%8===7&&this.#e.write(this.#r);e.length%8!==0&&this.#e.write(this.#r.subarray(0,e.length%8))}writeBox(e){if(this.offsets.set(e,this.#e.getPos()),e.contents&&!e.children)this.writeBoxHeader(e,e.size??e.contents.byteLength+8),this.#e.write(e.contents);else{let s=this.#e.getPos();if(this.writeBoxHeader(e,0),e.contents&&this.#e.write(e.contents),e.children)for(let a of e.children)a&&this.writeBox(a);let o=this.#e.getPos(),i=e.size??o-s;this.#e.seek(s),this.writeBoxHeader(e,i),this.#e.seek(o)}}writeBoxHeader(e,s){this.writeU32(e.largeSize?1:s),this.writeAscii(e.type),e.largeSize&&this.writeU64(s)}measureBoxHeader(e){return 8+(e.largeSize?8:0)}patchBox(e){let s=this.offsets.get(e);c(s!==void 0);let o=this.#e.getPos();this.#e.seek(s),this.writeBox(e),this.#e.seek(o)}measureBox(e){if(e.contents&&!e.children)return this.measureBoxHeader(e)+e.contents.byteLength;{let s=this.measureBoxHeader(e);if(e.contents&&(s+=e.contents.byteLength),e.children)for(let o of e.children)o&&(s+=this.measureBox(o));return s}}start(){this.#p()}#p(){let e=this.output.tracks.some(s=>s.type==="video"&&s.source.codec==="avc");if(this.writeBox(be({holdsAvc:e,fragmented:this.#t.options.fastStart==="fragmented"})),this.#n=this.#e.getPos(),this.#t.options.fastStart==="in-memory")this.#i=q(!1);else if(this.#t.options.fastStart!=="fragmented"){if(typeof this.#t.options.fastStart=="object"){let s=this.#b();this.#e.seek(this.#e.getPos()+s)}this.#i=q(!0),this.writeBox(this.#i)}this.#e.flush()}#b(){c(typeof this.#t.options.fastStart=="object");let e=0,s=[this.#t.options.fastStart.expectedVideoChunks,this.#t.options.fastStart.expectedAudioChunks];for(let o of s)o&&(e+=8*Math.ceil(2/3*o),e+=4*o,e+=12*Math.ceil(2/3*o),e+=4*o,e+=8*o);return e+=4096,e}#C(e,s,o){let i=this.#s.find(l=>l.track===e);if(i)return i;c(o),c(o.decoderConfig),c(o.decoderConfig.codedWidth),c(o.decoderConfig.codedHeight);let a={track:e,type:"video",info:{width:o.decoderConfig.codedWidth,height:o.decoderConfig.codedHeight,decoderConfig:o.decoderConfig},timescale:e.source.metadata.frameRate??57600,samples:[],sampleQueue:[],firstDecodeTimestamp:null,lastDecodeTimestamp:-1,timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[]};return this.#s.push(a),this.#s.sort((l,u)=>l.track.id-u.track.id),a}#T(e,s,o){let i=this.#s.find(l=>l.track===e);if(i)return i;c(o),c(o.decoderConfig);let a={track:e,type:"audio",info:{numberOfChannels:o.decoderConfig.numberOfChannels,sampleRate:o.decoderConfig.sampleRate,decoderConfig:o.decoderConfig},timescale:o.decoderConfig.sampleRate,samples:[],sampleQueue:[],firstDecodeTimestamp:null,lastDecodeTimestamp:-1,timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[]};return this.#s.push(a),this.#s.sort((l,u)=>l.track.id-u.track.id),a}addEncodedVideoChunk(e,s,o,i){let a=this.#C(e,s,o);if(typeof this.#t.options.fastStart=="object"&&a.samples.length===this.#t.options.fastStart.expectedVideoChunks)throw new Error(`Cannot add more video chunks than specified in 'fastStart' (${this.#t.options.fastStart.expectedVideoChunks}).`);let l=this.#d(a,s,i);this.#t.options.fastStart==="fragmented"?(a.sampleQueue.push(l),this.#f()):this.#l(a,l)}addEncodedAudioChunk(e,s,o){let i=this.#T(e,s,o);if(typeof this.#t.options.fastStart=="object"&&i.samples.length===this.#t.options.fastStart.expectedAudioChunks)throw new Error(`Cannot add more audio chunks than specified in 'fastStart' (${this.#t.options.fastStart.expectedAudioChunks}).`);let a=this.#d(i,s);this.#t.options.fastStart==="fragmented"?(i.sampleQueue.push(a),this.#f()):this.#l(i,a)}#d(e,s,o){let i=s.timestamp/1e6,a=(s.timestamp-(o??0))/1e6,l=(s.duration??0)/1e6,u=this.#g(e,i,a);i=u.presentationTimestamp,a=u.decodeTimestamp;let f=new Uint8Array(s.byteLength);return s.copyTo(f),{presentationTimestamp:i,decodeTimestamp:a,duration:l,data:f,size:f.byteLength,type:s.type,timescaleUnitsToNextSample:T(l,e.timescale)}}#l(e,s){this.#t.options.fastStart!=="fragmented"&&e.samples.push(s);let o=T(s.presentationTimestamp-s.decodeTimestamp,e.timescale);if(e.lastTimescaleUnits!==null){c(e.lastSample);let a=T(s.decodeTimestamp,e.timescale,!1),l=Math.round(a-e.lastTimescaleUnits);if(e.lastTimescaleUnits+=l,e.lastSample.timescaleUnitsToNextSample=l,this.#t.options.fastStart!=="fragmented"){let u=z(e.timeToSampleTable);c(u),u.sampleCount===1?(u.sampleDelta=l,u.sampleCount++):u.sampleDelta===l?u.sampleCount++:(u.sampleCount--,e.timeToSampleTable.push({sampleCount:2,sampleDelta:l}));let f=z(e.compositionTimeOffsetTable);c(f),f.sampleCompositionTimeOffset===o?f.sampleCount++:e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:o})}}else e.lastTimescaleUnits=0,this.#t.options.fastStart!=="fragmented"&&(e.timeToSampleTable.push({sampleCount:1,sampleDelta:T(s.duration,e.timescale)}),e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:o}));e.lastSample=s;let i=!1;if(!e.currentChunk)i=!0;else{let a=s.presentationTimestamp-e.currentChunk.startTimestamp;if(this.#t.options.fastStart==="fragmented"){let l=this.#s.every(u=>{if(e===u)return s.type==="key";let f=u.sampleQueue[0];return f&&f.type==="key"});a>=1&&l&&(i=!0,this.#m())}else i=a>=.5}i&&(e.currentChunk&&this.#c(e),e.currentChunk={startTimestamp:s.presentationTimestamp,samples:[],offset:null,moofOffset:null}),c(e.currentChunk),e.currentChunk.samples.push(s)}#g(e,s,o){if(e.firstDecodeTimestamp===null&&(e.firstDecodeTimestamp=o),o-=e.firstDecodeTimestamp,s-=e.firstDecodeTimestamp,o<e.lastDecodeTimestamp)throw new Error(`Timestamps must be monotonically increasing (timestamp went from ${e.lastDecodeTimestamp}s to ${o}s).`);return e.lastDecodeTimestamp=o,{presentationTimestamp:s,decodeTimestamp:o}}#c(e){if(c(this.#t.options.fastStart!=="fragmented"),!!e.currentChunk){if(e.finalizedChunks.push(e.currentChunk),this.#u.push(e.currentChunk),(e.compactlyCodedChunkTable.length===0||z(e.compactlyCodedChunkTable).samplesPerChunk!==e.currentChunk.samples.length)&&e.compactlyCodedChunkTable.push({firstChunk:e.finalizedChunks.length,samplesPerChunk:e.currentChunk.samples.length}),this.#t.options.fastStart==="in-memory"){e.currentChunk.offset=0;return}e.currentChunk.offset=this.#e.getPos();for(let s of e.currentChunk.samples)c(s.data),this.#e.write(s.data),s.data=null;this.#e.flush()}}#f(){if(c(this.#t.options.fastStart==="fragmented"),!(this.#s.length<this.output.tracks.length))e:for(;;){let e=null,s=1/0;for(let i of this.#s){if(i.sampleQueue.length===0)break e;i.sampleQueue[0].decodeTimestamp<s&&(e=i,s=i.sampleQueue[0].decodeTimestamp)}if(!e)break;let o=e.sampleQueue.shift();this.#l(e,o)}}#m(e=!0){c(this.#t.options.fastStart==="fragmented");let s=this.#h++;if(s===1){let u=U(this.#s,this.#a,!0);this.writeBox(u)}let o=this.#e.getPos(),i=ne(s,this.#s);this.writeBox(i);{let u=q(!1),f=0;for(let E of this.#s){c(E.currentChunk);for(let N of E.currentChunk.samples)f+=N.size}let y=this.measureBox(u)+f;y>=2**32&&(u.largeSize=!0,y=this.measureBox(u)+f),u.size=y,this.writeBox(u)}for(let u of this.#s){u.currentChunk.offset=this.#e.getPos(),u.currentChunk.moofOffset=o;for(let f of u.currentChunk.samples)this.#e.write(f.data),f.data=null}let a=this.#e.getPos();this.#e.seek(this.offsets.get(i));let l=ne(s,this.#s);this.writeBox(l),this.#e.seek(a);for(let u of this.#s)u.finalizedChunks.push(u.currentChunk),this.#u.push(u.currentChunk),u.currentChunk=null;e&&this.#e.flush()}finalize(){if(this.#t.options.fastStart==="fragmented"){for(let e of this.#s)for(let s of e.sampleQueue)this.#l(e,s);this.#m(!1)}else for(let e of this.#s)this.#c(e);if(this.#t.options.fastStart==="in-memory"){c(this.#i);let e;for(let o=0;o<2;o++){let i=U(this.#s,this.#a),a=this.measureBox(i);e=this.measureBox(this.#i);let l=this.#e.getPos()+a+e;for(let u of this.#u){u.offset=l;for(let{data:f}of u.samples)c(f),l+=f.byteLength,e+=f.byteLength}if(l<2**32)break;e>=2**32&&(this.#i.largeSize=!0)}let s=U(this.#s,this.#a);this.writeBox(s),this.#i.size=e,this.writeBox(this.#i);for(let o of this.#u)for(let i of o.samples)c(i.data),this.#e.write(i.data),i.data=null}else if(this.#t.options.fastStart==="fragmented"){let e=this.#e.getPos(),s=ge(this.#s);this.writeBox(s);let o=this.#e.getPos()-e;this.#e.seek(this.#e.getPos()-4),this.writeU32(o)}else{c(this.#i),c(this.#n!==null);let e=this.offsets.get(this.#i);c(e!==void 0);let s=this.#e.getPos()-e;this.#i.size=s,this.#i.largeSize=s>=2**32,this.patchBox(this.#i);let o=U(this.#s,this.#a);if(typeof this.#t.options.fastStart=="object"){this.#e.seek(this.#n),this.writeBox(o);let i=e-this.#e.getPos();this.writeBox(Ce(i))}else this.writeBox(o)}}};var ae=class{},G=class extends ae{constructor(e){super();this.options=e}createMuxer(e){return new X(e,this)}};var F=class{},Y=class extends F{#e=0;#t;#r=new ArrayBuffer(2**16);#o=new Uint8Array(this.#r);#n=0;constructor(r){super(),this.#t=r}#i(r){let e=this.#r.byteLength;for(;e<r;)e*=2;if(e===this.#r.byteLength)return;let s=new ArrayBuffer(e),o=new Uint8Array(s);o.set(this.#o,0),this.#r=s,this.#o=o}write(r){this.#i(this.#e+r.byteLength),this.#o.set(r,this.#e),this.#e+=r.byteLength,this.#n=Math.max(this.#n,this.#e)}seek(r){this.#e=r}getPos(){return this.#e}flush(){}finalize(){this.#i(this.#e),this.#t.buffer=this.#r.slice(0,Math.max(this.#n,this.#e))}},Z=class extends F{#e=0;#t;#r=[];constructor(r){super(),this.#t=r}write(r){this.#r.push({data:r.slice(),start:this.#e}),this.#e+=r.byteLength}seek(r){this.#e=r}getPos(){return this.#e}flush(){if(this.#r.length===0)return;let r=[],e=[...this.#r].sort((s,o)=>s.start-o.start);r.push({start:e[0].start,size:e[0].data.byteLength});for(let s=1;s<e.length;s++){let o=r[r.length-1],i=e[s];i.start<=o.start+o.size?o.size=Math.max(o.size,i.start+i.data.byteLength-o.start):r.push({start:i.start,size:i.data.byteLength})}for(let s of r){s.data=new Uint8Array(s.size);for(let o of this.#r)s.start<=o.start&&o.start<s.start+s.size&&s.data.set(o.data,o.start-s.start);this.#t.options.onData?.(s.data,s.start)}this.#r.length=0}finalize(){}},bt=2**24,Ct=2,P=class extends F{#e=0;#t;#r;#o=[];constructor(r){if(super(),this.#t=r,this.#r=r.options?.chunkSize??bt,!Number.isInteger(this.#r)||this.#r<2**10)throw new Error("Invalid StreamTarget options: chunkSize must be an integer not smaller than 1024.")}write(r){this.#n(r,this.#e),this.#a(),this.#e+=r.byteLength}seek(r){this.#e=r}getPos(){return this.#e}#n(r,e){let s=this.#o.findIndex(u=>u.start<=e&&e<u.start+this.#r);s===-1&&(s=this.#s(e));let o=this.#o[s],i=e-o.start,a=r.subarray(0,Math.min(this.#r-i,r.byteLength));o.data.set(a,i);let l={start:i,end:i+a.byteLength};if(this.#i(o,l),o.written[0].start===0&&o.written[0].end===this.#r&&(o.shouldFlush=!0),this.#o.length>Ct){for(let u=0;u<this.#o.length-1;u++)this.#o[u].shouldFlush=!0;this.#a()}a.byteLength<r.byteLength&&this.#n(r.subarray(a.byteLength),e+a.byteLength)}#i(r,e){let s=0,o=r.written.length-1,i=-1;for(;s<=o;){let a=Math.floor(s+(o-s+1)/2);r.written[a].start<=e.start?(s=a+1,i=a):o=a-1}for(r.written.splice(i+1,0,e),(i===-1||r.written[i].end<e.start)&&i++;i<r.written.length-1&&r.written[i].end>=r.written[i+1].start;)r.written[i].end=Math.max(r.written[i].end,r.written[i+1].end),r.written.splice(i+1,1)}#s(r){let s={start:Math.floor(r/this.#r)*this.#r,data:new Uint8Array(this.#r),written:[],shouldFlush:!1};return this.#o.push(s),this.#o.sort((o,i)=>o.start-i.start),this.#o.indexOf(s)}#a(r=!1){for(let e=0;e<this.#o.length;e++){let s=this.#o[e];if(!(!s.shouldFlush&&!r)){for(let o of s.written)this.#t.options.onData?.(s.data.subarray(o.start,o.end),s.start+o.start);this.#o.splice(e--,1)}}}flush(){}finalize(){this.#a(!0)}},J=class extends P{constructor(r){super(new I({onData:(e,s)=>r.stream.write({type:"write",data:e,position:s}),chunkSize:r.options?.chunkSize}))}};var Tt=Symbol("isTarget");Tt;var O=class{},ee=class extends O{constructor(){super(...arguments);this.buffer=null}createWriter(){return new Y(this)}},I=class extends O{constructor(e){super();this.options=e;if(typeof e!="object")throw new TypeError("StreamTarget requires an options object to be passed to its constructor.");if(e.onData){if(typeof e.onData!="function")throw new TypeError("options.onData, when provided, must be a function.");if(e.onData.length<2)throw new TypeError("options.onData, when provided, must be a function that takes in at least two arguments (data and position). Ignoring the position argument, which specifies the byte offset at which the data is to be written, can lead to broken outputs.")}if(e.chunked!==void 0&&typeof e.chunked!="boolean")throw new TypeError("options.chunked, when provided, must be a boolean.");if(e.chunkSize!==void 0&&(!Number.isInteger(e.chunkSize)||e.chunkSize<=0))throw new TypeError("options.chunkSize, when provided, must be a positive integer.")}createWriter(){return this.options.chunked?new P(this):new Z(this)}},te=class extends O{constructor(e,s){super();this.stream=e;this.options=s;if(!(e instanceof FileSystemWritableFileStream))throw new TypeError("FileSystemWritableFileStreamTarget requires a FileSystemWritableFileStream instance.");if(s!==void 0&&typeof s!="object")throw new TypeError("FileSystemWritableFileStreamTarget's options, when provided, must be an object.");if(s&&s.chunkSize!==void 0&&(!Number.isInteger(s.chunkSize)||s.chunkSize<=0))throw new TypeError("options.chunkSize, when provided, must be a positive integer")}createWriter(){return new J(this)}};return ve(gt);})();
|
|
if (typeof module === "object" && typeof module.exports === "object") Object.assign(module.exports, Metamuxer)
|