@@ -351,7 +351,10 @@ UniqueAVFrame AudioEncoder::maybeConvertAVFrame(const UniqueAVFrame& avFrame) {
351351void AudioEncoder::encodeFrameThroughFifo (
352352 AutoAVPacket& autoAVPacket,
353353 const UniqueAVFrame& avFrame,
354- bool andFlushFifo) {
354+ // flushFifo is only set to true in maybeFlushSwrBuffers(), i.e. at the very
355+ // end of the encoding process when we're flushing buffers. We also want to
356+ // flush the FIFO so as to not leave any remaining samples in it.
357+ bool flushFifo) {
355358 if (avAudioFifo_ == nullptr ) {
356359 encodeFrame (autoAVPacket, avFrame);
357360 return ;
@@ -373,8 +376,20 @@ void AudioEncoder::encodeFrameThroughFifo(
373376 outNumChannels_,
374377 avCodecContext_->sample_fmt );
375378
379+ // Explaining the while bound:
380+ // - if we're not flushing the FIFO, i.e. in most cases, we want to pull
381+ // exactly `frame_size` samples from the FIFO, so we have to stop before it
382+ // contains less than `frame_size` samples.
383+ // - if we're flushing the FIFO, we want to read from the FIFO until the very
384+ // last sample it contains.
385+ //
386+ // In both cases, for as long as we can, we're trying to pull exatly
387+ // `frame_size` samples from the FIFO and send each `frame_size`-sized avFrame
388+ // to encodeFrame(). Only the very last avFrame of the encoding process is
389+ // allowed to contained less than frame_size samples. That only happens when
390+ // flushFifo is true.
376391 while (av_audio_fifo_size (avAudioFifo_.get ()) >=
377- (andFlushFifo ? 1 : avCodecContext_->frame_size )) {
392+ (flushFifo ? 1 : avCodecContext_->frame_size )) {
378393 int samplesToRead = std::min (
379394 av_audio_fifo_size (avAudioFifo_.get ()), newavFrame->nb_samples );
380395 int numSamplesRead = av_audio_fifo_read (
@@ -466,7 +481,9 @@ void AudioEncoder::maybeFlushSwrBuffers(AutoAVPacket& autoAVPacket) {
466481 swrContext_.get (), avFrame->data , avFrame->nb_samples , NULL , 0 );
467482 avFrame->nb_samples = actualNumRemainingSamples;
468483
469- encodeFrameThroughFifo (autoAVPacket, avFrame, /* andFlushFifo=*/ true );
484+ // We're potentially sending avFrame through the FIFO (if it exists), in which
485+ // case we also want to flush the FIFO itself.
486+ encodeFrameThroughFifo (autoAVPacket, avFrame, /* flushFifo=*/ true );
470487}
471488
472489void AudioEncoder::flushBuffers () {
0 commit comments