From c56f42d9805f70b416bfb1b565b1022d99a67fcf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=A4lim=C3=A4ki=20Tuomas?= Date: Tue, 13 Aug 2024 08:14:07 +0300 Subject: [PATCH] Write OPUS control header in TSMuxer. --- .../streampack/internal/muxers/ts/TSMuxer.kt | 35 +++++++++++++++++-- 1 file changed, 33 insertions(+), 2 deletions(-) diff --git a/core/src/main/java/io/github/thibaultbee/streampack/internal/muxers/ts/TSMuxer.kt b/core/src/main/java/io/github/thibaultbee/streampack/internal/muxers/ts/TSMuxer.kt index 5de15ce41..235912fdf 100644 --- a/core/src/main/java/io/github/thibaultbee/streampack/internal/muxers/ts/TSMuxer.kt +++ b/core/src/main/java/io/github/thibaultbee/streampack/internal/muxers/ts/TSMuxer.kt @@ -150,8 +150,14 @@ class TSMuxer( } MediaFormat.MIMETYPE_AUDIO_OPUS -> { - frame - } // TODO: optional control header + val payload = frame.rawBuffer + val controlHeader = opusControlHeader(payload.remaining()) + val opusAccessUnit = ByteBuffer.allocate(controlHeader.remaining() + payload.remaining()) + opusAccessUnit.put(controlHeader) + opusAccessUnit.put(payload) + opusAccessUnit.rewind() + frame.copy(rawBuffer = opusAccessUnit) + } else -> throw IllegalArgumentException("Unsupported mimeType ${frame.mimeType}") } @@ -160,6 +166,31 @@ class TSMuxer( } } + private fun opusControlHeader(payloadSize: Int): ByteBuffer { + val payloadSizeFullBytesCount = payloadSize / 255 + val payloadSizeRemainderByte = payloadSize % 255 + val headerSize = 2 + payloadSizeFullBytesCount + payloadSizeRemainderByte.coerceAtMost(1) + val header = ByteBuffer.allocate(headerSize) + + // control_header_prefix 11 bits (0x3FF or 01111111111) + // start_trim_flag 1 bit (0) + // end_trim_flag 1 bit (0) + // control_extension_flag 1 bit (0) + // reserved 2 bits (0) + header.put(0x7F.toByte()) + header.put(0xE0.toByte()) + + repeat(payloadSizeFullBytesCount) { + header.put(0xFF.toByte()) + } + if (payloadSizeRemainderByte > 0) { + header.put(payloadSizeRemainderByte.toByte()) + } + + header.rewind() + return header + } + /** * Generate MPEG-TS table and elementary stream from the frame * @param pes Pes containing infos on the stream