import{Muxer as l}from"../muxer.js";import{parsePcmCodec as W,validateAudioChunkMetadata as m}from"../codec.js";import{WaveFormat as s}from"./wave-demuxer.js";import{RiffWriter as c}from"./riff-writer.js";import{assert as n}from"../misc.js";export class WaveMuxer extends l{constructor(e,i){super(e),this.headerWritten=!1,this.dataSize=0,this.sampleRate=null,this.sampleCount=0,this.format=i,this.writer=e._writer,this.riffWriter=new c(e._writer),this.isRf64=!!i._options.large}async start(){}async getMimeType(){return"audio/wav"}async addEncodedVideoPacket(){throw new Error("WAVE does not support video.")}async addEncodedAudioPacket(e,i,t){const f=await this.mutex.acquire();try{if(this.headerWritten||(m(t),n(t),n(t.decoderConfig),this.writeHeader(e,t.decoderConfig),this.sampleRate=t.decoderConfig.sampleRate,this.headerWritten=!0),this.validateAndNormalizeTimestamp(e,i.timestamp,i.type==="key"),!this.isRf64&&this.writer.getPos()+i.data.byteLength>=2**32)throw new Error("Adding more audio data would exceed the maximum RIFF size of 4 GiB. To write larger files, use RF64 by setting `large: true` in the WavOutputFormatOptions.");this.writer.write(i.data),this.dataSize+=i.data.byteLength,this.sampleCount+=Math.round(i.duration*this.sampleRate),await this.writer.flush()}finally{f()}}async addSubtitleCue(){throw new Error("WAVE does not support subtitles.")}writeHeader(e,i){this.format._options.onHeader&&this.writer.startTrackingWrites();let t;const f=e.source._codec,r=W(f);r.dataType==="ulaw"?t=s.MULAW:r.dataType==="alaw"?t=s.ALAW:r.dataType==="float"?t=s.IEEE_FLOAT:t=s.PCM;const a=i.numberOfChannels,o=i.sampleRate,h=r.sampleSize*a;if(this.riffWriter.writeAscii(this.isRf64?"RF64":"RIFF"),this.isRf64?this.riffWriter.writeU32(4294967295):this.riffWriter.writeU32(0),this.riffWriter.writeAscii("WAVE"),this.isRf64&&(this.riffWriter.writeAscii("ds64"),this.riffWriter.writeU32(28),this.riffWriter.writeU64(0),this.riffWriter.writeU64(0),this.riffWriter.writeU64(0),this.riffWriter.writeU32(0)),this.riffWriter.writeAscii("fmt "),this.riffWriter.writeU32(16),this.riffWriter.writeU16(t),this.riffWriter.writeU16(a),this.riffWriter.writeU32(o),this.riffWriter.writeU32(o*h),this.riffWriter.writeU16(h),this.riffWriter.writeU16(8*r.sampleSize),this.riffWriter.writeAscii("data"),this.isRf64?this.riffWriter.writeU32(4294967295):this.riffWriter.writeU32(0),this.format._options.onHeader){const{data:d,start:w}=this.writer.stopTrackingWrites();this.format._options.onHeader(d,w)}}async finalize(){const e=await this.mutex.acquire(),i=this.writer.getPos();this.isRf64?(this.writer.seek(20),this.riffWriter.writeU64(i-8),this.writer.seek(28),this.riffWriter.writeU64(this.dataSize),this.writer.seek(36),this.riffWriter.writeU64(this.sampleCount)):(this.writer.seek(4),this.riffWriter.writeU32(i-8),this.writer.seek(40),this.riffWriter.writeU32(this.dataSize)),this.writer.seek(i),e()}}
