MCPcopy Create free account
hub / github.com/Vanilagy/webcodecs-polyfill / encodeInternal

Method encodeInternal

src/audio_encoder.ts:334–431  ·  view source on GitHub ↗
(clonedData: AudioData)

Source from the content-addressed store, hash-verified

332 }
333
334 private async encodeInternal(clonedData: AudioData) {
335 const currentConfigId = this.currentConfigId;
336
337 using lock = this.mutex.lock();
338 await lock.ready; // Unconditional await here to queue a microtask
339
340 if (this.currentConfigId !== currentConfigId) {
341 clonedData.close();
342 return;
343 }
344
345 // Spec: Decrement [[encodeQueueSize]] and run the Schedule Dequeue Event algorithm.
346 this.decrementQueue();
347
348 try {
349 assert(this.codecContext);
350
351 if (clonedData instanceof AudioDataPolyfill && clonedData._data instanceof Frame) {
352 const otherFrame = clonedData._data;
353 this.frame.ref(otherFrame);
354 } else {
355 // Copy audio data from AudioData to FFmpeg Frame
356 const format = fromAudioSampleFormat(clonedData.format!);
357 this.frame.format = format;
358 this.frame.nbSamples = clonedData.numberOfFrames;
359 this.frame.sampleRate = clonedData.sampleRate;
360 this.frame.channelLayout = getChannelLayout(clonedData.numberOfChannels);
361 this.frame.pts = BigInt(clonedData.timestamp);
362 this.frame.duration = BigInt(clonedData.duration);
363
364 // Allocate buffer and copy data
365 this.frame.allocBuffer();
366
367 // Copy data from AudioData to frame buffer
368 const size = clonedData.allocationSize({ planeIndex: 0 });
369 const buffer = Buffer.alloc(size);
370 clonedData.copyTo(buffer, { planeIndex: 0 });
371 this.frame.fromBuffer(buffer);
372 }
373 } finally {
374 clonedData.close();
375 }
376
377 // We need the resampler when:
378 // 1. Format conversion is needed (sample format, sample rate, or channel count differs)
379 // 2. The codec requires fixed frame sizes
380 const requiresResampler
381 = this.codecContext.frameSize > 0
382 || this.codecContext.sampleFormat !== this.frame.format
383 || this.codecContext.sampleRate !== this.frame.sampleRate
384 || this.codecContext.channels !== this.frame.channels;
385
386 if (requiresResampler) {
387 if (!this.resampler) {
388 this.resampler = new SoftwareResampleContext();
389 }
390
391 const key = `${this.frame.sampleRate}:${this.frame.channels}:${this.frame.format}`;

Callers 1

encodeMethod · 0.95

Calls 10

decrementQueueMethod · 0.95
pullResampledFramesMethod · 0.95
assertFunction · 0.85
fromAudioSampleFormatFunction · 0.85
getChannelLayoutFunction · 0.85
lockMethod · 0.80
closeMethod · 0.45
allocationSizeMethod · 0.45
copyToMethod · 0.45

Tested by

no test coverage detected