|
| 1 | +package com.otaliastudios.transcoder.postprocessor; |
| 2 | + |
| 3 | +import androidx.annotation.NonNull; |
| 4 | + |
| 5 | +import java.nio.ShortBuffer; |
| 6 | + |
| 7 | +import static java.lang.Math.min; |
| 8 | + |
| 9 | +public class MixerTargetAudioPostProcessor implements AudioPostProcessor { |
| 10 | + private MixerSourceAudioPostProcessor mSource; |
| 11 | + private float mSourceVolume; |
| 12 | + private float mTargetVolume; |
| 13 | + |
| 14 | + @Override |
| 15 | + public long calculateNewDurationUs(long durationUs) { |
| 16 | + return durationUs; |
| 17 | + } |
| 18 | + |
| 19 | + public MixerTargetAudioPostProcessor(MixerSourceAudioPostProcessor source, float sourceVolume, float targetVolume) |
| 20 | + { |
| 21 | + mSource = source; |
| 22 | + mSourceVolume = sourceVolume; |
| 23 | + mTargetVolume = targetVolume; |
| 24 | + } |
| 25 | + |
| 26 | + private short mixSamples(short sourceSample, short targetSample) { |
| 27 | + float mixedSample = (sourceSample * mSourceVolume) + (targetSample * mTargetVolume); |
| 28 | + if (mixedSample < Short.MIN_VALUE) |
| 29 | + mixedSample = Short.MIN_VALUE; |
| 30 | + else if (mixedSample > Short.MAX_VALUE) |
| 31 | + mixedSample = Short.MAX_VALUE; |
| 32 | + return (short)mixedSample; |
| 33 | + } |
| 34 | + |
| 35 | + @Override |
| 36 | + public long postProcess(@NonNull ShortBuffer inputBuffer, @NonNull ShortBuffer outputBuffer, long bufferDurationUs) { |
| 37 | + ShortBuffer sourceBuffer = mSource.mBuffers.peek(); |
| 38 | + int inputRemaining = inputBuffer.remaining(); |
| 39 | + while (sourceBuffer != null && inputRemaining > 0) { |
| 40 | + int sourceRemaining = sourceBuffer.remaining(); |
| 41 | + int remaining = min(inputRemaining, sourceRemaining); |
| 42 | + for (int i=0; i<remaining; i++) { |
| 43 | + outputBuffer.put(mixSamples(sourceBuffer.get(), inputBuffer.get())); |
| 44 | + } |
| 45 | + inputRemaining -= sourceRemaining; |
| 46 | + if (inputRemaining >= 0) { |
| 47 | + mSource.mBuffers.remove(); |
| 48 | + sourceBuffer = mSource.mBuffers.peek(); |
| 49 | + } |
| 50 | + } |
| 51 | + outputBuffer.put(inputBuffer); |
| 52 | + return bufferDurationUs; |
| 53 | + } |
| 54 | +} |
0 commit comments