For a testing purpose I am creating a new video from existing one by using MediaExtractor and MediaMuxer. I expect the new video to be exactly the same duration as the original one but it is not the case. The new video duration is slightly shorter than the original one.
fun test(firstVideo: FileDescriptor, outputFileAbsolutePathUri: String) {
val extractor = MediaExtractor().apply {
this.setDataSource(firstVideo)
}
val muxer = MediaMuxer(outputFileAbsolutePathUri, MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4)
try {
val MAX_SAMPLE_SIZE = 20 * 1024 * 1024
val bufferSize: Int = MAX_SAMPLE_SIZE
val dstBuf: ByteBuffer = ByteBuffer.allocate(bufferSize)
val bufferInfo = MediaCodec.BufferInfo()
val indexMap = setMuxerTracks(extractor, muxer)
muxer.start()
muxDataFromExtractor(muxer, extractor, indexMap, dstBuf, bufferInfo)
muxer.stop()
} finally {
extractor.release()
muxer.release()
}
}
private fun setMuxerTracks(extractor: MediaExtractor, muxer: MediaMuxer): Map<Int, Int> {
val indexMap = HashMap<Int, Int>(extractor.trackCount)
for (i in 0 until extractor.trackCount) {
extractor.selectTrack(i)
val format: MediaFormat = extractor.getTrackFormat(i)
val dstIndex = muxer.addTrack(format)
indexMap[i] = dstIndex
}
return indexMap
}
private fun muxDataFromExtractor(muxer: MediaMuxer,
extractor: MediaExtractor,
trackIndexMap: Map<Int, Int>,
dstBuf: ByteBuffer,
bufferInfo: MediaCodec.BufferInfo) {
var sawEOS = false
val initialPresentationTimeUs = bufferInfo.presentationTimeUs
while (!sawEOS) {
bufferInfo.offset = 0
bufferInfo.size = extractor.readSampleData(dstBuf, 0)
if (bufferInfo.size < 0) {
sawEOS = true
bufferInfo.size = 0
} else {
bufferInfo.presentationTimeUs = initialPresentationTimeUs + extractor.sampleTime
bufferInfo.flags = extractor.sampleFlags
val trackIndex = extractor.sampleTrackIndex
muxer.writeSampleData(trackIndexMap[trackIndex]!!, dstBuf, bufferInfo)
extractor.advance()
}
}
}
Just for the sake of comparison the original video duration was 3366666 microsec and the created video duration was 3366366 microseconds. The video length is retrieved from MediaFormat (MediaFormat.KEY_DURATION)
It appears that it depends on the way the source video was created: When I used ffprobe to get source video metadata I got the following:
The result video metadata was:
When I use the video that was created by using MediaExtractor and MediaMuxer as a source the video duration is the same (within 1 microsecond threshold)