Skip to content

Close avio object *before* encode destruction. And flush, too. #773

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 14 additions & 2 deletions src/torchcodec/_core/Encoder.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -99,8 +99,18 @@ AVSampleFormat findBestOutputSampleFormat(const AVCodec& avCodec) {
} // namespace

AudioEncoder::~AudioEncoder() {
if (avFormatContext_ && avFormatContext_->pb && !avioContextHolder_) {
avio_close(avFormatContext_->pb);
close_avio();
}

void AudioEncoder::close_avio() {
if (avFormatContext_ && avFormatContext_->pb) {
avio_flush(avFormatContext_->pb);

if (!avioContextHolder_) {
avio_close(avFormatContext_->pb);
// avoids closing again in destructor, which would segfault.
avFormatContext_->pb = nullptr;
}
}
}

Expand Down Expand Up @@ -308,6 +318,8 @@ void AudioEncoder::encode() {
status == AVSUCCESS,
"Error in: av_write_trailer",
getFFMPEGErrorStringFromErrorCode(status));

close_avio();
}

UniqueAVFrame AudioEncoder::maybeConvertAVFrame(const UniqueAVFrame& avFrame) {
Expand Down
1 change: 1 addition & 0 deletions src/torchcodec/_core/Encoder.h
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ class AudioEncoder {
void encodeFrame(AutoAVPacket& autoAVPacket, const UniqueAVFrame& avFrame);
void maybeFlushSwrBuffers(AutoAVPacket& autoAVPacket);
void flushBuffers();
void close_avio();

UniqueEncodingAVFormatContext avFormatContext_;
UniqueAVCodecContext avCodecContext_;
Expand Down
Loading