Skip to content

Commit b87f00d

Browse files
authored
Avoid unnecessary calls to avcodec_receive_frame in decoding loop (#502)
1 parent 79c3934 commit b87f00d

File tree

1 file changed

+26
-25
lines changed

1 file changed

+26
-25
lines changed

src/torchcodec/decoders/_core/VideoDecoder.cpp

Lines changed: 26 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -971,43 +971,44 @@ VideoDecoder::AVFrameStream VideoDecoder::decodeAVFrame(
971971
}
972972

973973
if (reachedEOF) {
974-
// We don't have any more packets to send to the decoder. So keep on
975-
// pulling frames from its internal buffers.
974+
// We don't have any more packets to receive. So keep on pulling frames
975+
// from its internal buffers.
976976
continue;
977977
}
978978

979979
// We still haven't found the frame we're looking for. So let's read more
980980
// packets and send them to the decoder.
981981
ReferenceAVPacket packet(autoAVPacket);
982-
ffmpegStatus = av_read_frame(formatContext_.get(), packet.get());
983-
decodeStats_.numPacketsRead++;
982+
do {
983+
ffmpegStatus = av_read_frame(formatContext_.get(), packet.get());
984+
decodeStats_.numPacketsRead++;
985+
986+
if (ffmpegStatus == AVERROR_EOF) {
987+
// End of file reached. We must drain the codec by sending a nullptr
988+
// packet.
989+
ffmpegStatus = avcodec_send_packet(
990+
streamInfo.codecContext.get(),
991+
/*avpkt=*/nullptr);
992+
if (ffmpegStatus < AVSUCCESS) {
993+
throw std::runtime_error(
994+
"Could not flush decoder: " +
995+
getFFMPEGErrorStringFromErrorCode(ffmpegStatus));
996+
}
997+
998+
reachedEOF = true;
999+
break;
1000+
}
9841001

985-
if (ffmpegStatus == AVERROR_EOF) {
986-
// End of file reached. We must drain the codec by sending a nullptr
987-
// packet.
988-
ffmpegStatus = avcodec_send_packet(
989-
streamInfo.codecContext.get(),
990-
/*avpkt=*/nullptr);
9911002
if (ffmpegStatus < AVSUCCESS) {
9921003
throw std::runtime_error(
993-
"Could not flush decoder: " +
1004+
"Could not read frame from input file: " +
9941005
getFFMPEGErrorStringFromErrorCode(ffmpegStatus));
9951006
}
1007+
} while (packet->stream_index != activeStreamIndex_);
9961008

997-
// We've reached the end of file so we can't read any more packets from
998-
// it, but the decoder may still have frames to read in its buffer.
999-
// Continue iterating to try reading frames.
1000-
reachedEOF = true;
1001-
continue;
1002-
}
1003-
1004-
if (ffmpegStatus < AVSUCCESS) {
1005-
throw std::runtime_error(
1006-
"Could not read frame from input file: " +
1007-
getFFMPEGErrorStringFromErrorCode(ffmpegStatus));
1008-
}
1009-
1010-
if (packet->stream_index != activeStreamIndex_) {
1009+
if (reachedEOF) {
1010+
// We don't have any more packets to send to the decoder. So keep on
1011+
// pulling frames from its internal buffers.
10111012
continue;
10121013
}
10131014

0 commit comments

Comments
 (0)