justdan96 / tsMuxer

tsMuxer is a transport stream muxer for remuxing/muxing elementary streams, EVO/VOB/MPG, MKV/MKA, MP4/MOV, TS, M2TS to TS to M2TS. Supported video codecs H.264/AVC, H.265/HEVC, VC-1, MPEG2. Supported audio codecs AAC, AC3 / E-AC3(DD+), DTS/ DTS-HD.
Apache License 2.0
829 stars 140 forks source link

Fix race condtion that cause corrupted tail of output TS #875

Open moveman opened 1 month ago

moveman commented 1 month ago

We found that occasioinally the tail of the TS output is corrupted. After some debugging and guessing, the problem should be caused by this code

m_nothingToExecute = m_writeQueue.empty();

This code is not atomic. It is equivalent to this:

bool flag = m_writeQueue.empty();
m_nothingToExecute = flag;

Other threads could jump in after the first line and before the second line. This includes BufferedFileWriter::addWriterData(). When addWriteData() is indeed be called, the situation will be like this:

bool flag = m_writeQueue.empty(); // (true)

  m_nothingToExecute = false;
  m_writeQueue.push(data);

m_nothingToExecute = flag; // (true)

writeQueue is inserted a data and is NOT empty; however, m_nothingToExecute is set to true by the final line. That will cause waitForWriting() to return and then close() is called before the remaining byte is flushed to the output.

ValeZAA commented 1 month ago

Can you provide a sample source file and output: before and after?