Refactor logic to close AVIOContext #1144
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
This PR consolidates the logic used to flush and close
AVIOContext, and should fix the flaky test bug described in #724.The issue is related to the member variables
avFormatContext_andavioContextHolder_pointing to the sameAVIOContextobject, and the logic ofclose_avio.torchcodec/src/torchcodec/_core/Encoder.cpp
Line 185 in 50686bb
In
close_avio, ifavioContextHolder_is not defined (if usingto_file), theAVIOContextpointer is correctly set tonullptr, preventing double frees in the member variables destructors. Otherwise, it will be destroyed in the member variable destructors. In those destructors, both will attempt to free the same address, as it is never set to anullptr:torchcodec/src/torchcodec/_core/AVIOContextHolder.cpp
Lines 50 to 54 in 50686bb
torchcodec/src/torchcodec/_core/FFMPEGCommon.h
Lines 68 to 70 in 50686bb
The updated
closeAVIOContextfunction avoids this byavFormatContext_oravFormatContext_->pbare set tonullptr(so it is safe to call multiple times).avio_closeon theAVIOContextpointer ifavioContextHolder_is not defined (when usingto_file). Otherwise, the reference inavFormatContext_will be set tonullptr.avioContextHolder's destructor, theAVIOContextwill be freed (only once!).