Fix audio PTS by the duration of 1 sample

If the difference of PTS between two consecutive blocks of audio is less
than 1 sample, then it will be considered as non-increasing by FFmpeg
muxers having a time_base of 1/sample_rate.

Increase the PTS by 1 sample instead.
This commit is contained in:
Romain Vimont 2023-11-14 09:40:42 +01:00
parent a402eac7f2
commit 4b4f045e19
1 changed files with 4 additions and 2 deletions

View File

@ -29,6 +29,8 @@ public final class AudioCapture {
// receive 4 successive blocks without waiting, then we wait for the 4 next ones). // receive 4 successive blocks without waiting, then we wait for the 4 next ones).
public static final int MAX_READ_SIZE = 1024 * CHANNELS * BYTES_PER_SAMPLE; public static final int MAX_READ_SIZE = 1024 * CHANNELS * BYTES_PER_SAMPLE;
private static final long ONE_SAMPLE_US = (1000000 + SAMPLE_RATE - 1) / SAMPLE_RATE; // 1 sample in microseconds (used for fixing PTS)
private final int audioSource; private final int audioSource;
private AudioRecord recorder; private AudioRecord recorder;
@ -160,13 +162,13 @@ public final class AudioCapture {
long durationUs = r * 1000000 / (CHANNELS * BYTES_PER_SAMPLE * SAMPLE_RATE); long durationUs = r * 1000000 / (CHANNELS * BYTES_PER_SAMPLE * SAMPLE_RATE);
nextPts = pts + durationUs; nextPts = pts + durationUs;
if (previousPts != 0 && pts < previousPts) { if (previousPts != 0 && pts < previousPts + ONE_SAMPLE_US) {
// Audio PTS may come from two sources: // Audio PTS may come from two sources:
// - recorder.getTimestamp() if the call works; // - recorder.getTimestamp() if the call works;
// - an estimation from the previous PTS and the packet size as a fallback. // - an estimation from the previous PTS and the packet size as a fallback.
// //
// Therefore, the property that PTS are monotonically increasing is no guaranteed in corner cases, so enforce it. // Therefore, the property that PTS are monotonically increasing is no guaranteed in corner cases, so enforce it.
pts = previousPts + 1; pts = previousPts + ONE_SAMPLE_US;
} }
previousPts = pts; previousPts = pts;