ScreenAudioCapturer.kt
11.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
/*
* Copyright 2024-2025 LiveKit, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.livekit.android.audio
import android.Manifest
import android.annotation.SuppressLint
import android.media.AudioAttributes
import android.media.AudioFormat
import android.media.AudioPlaybackCaptureConfiguration
import android.media.AudioRecord
import android.media.projection.MediaProjection
import android.os.Build
import androidx.annotation.RequiresApi
import androidx.annotation.RequiresPermission
import io.livekit.android.room.track.LocalVideoTrack
import io.livekit.android.room.track.Track
import io.livekit.android.util.LKLog
import livekit.org.webrtc.ScreenCapturerAndroid
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.nio.FloatBuffer
import java.nio.ShortBuffer
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.roundToInt
private const val BUFFER_SIZE_FACTOR = 2
private const val MIN_GAIN_CHANGE = 0.01f
private const val DEFAULT_GAIN = 1f
private val DEFAULT_CONFIGURATOR: AudioPlaybackCaptureConfigurator = { builder ->
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
builder.addMatchingUsage(AudioAttributes.USAGE_UNKNOWN)
builder.addMatchingUsage(AudioAttributes.USAGE_MEDIA)
builder.addMatchingUsage(AudioAttributes.USAGE_GAME)
}
}
/**
* A mixer for capturing screen share audio.
*
* Requires a media projection, which can be obtained from the screen share track.
*
* Additionally, for screen capture to work properly while your app is in the
* background, a foreground service with the type `microphone` must be running.
* Otherwise, audio capture will not return any audio data.
*
* Example usage:
* ```
* suspend fun startScreenCapture(data: Intent) {
* if (ActivityCompat.checkSelfPermission(getApplication(), Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
* return
* }
*
* // Publish the screen share video.
* room.localParticipant.setScreenShareEnabled(true, data)
*
* // Optionally disable the mic for screenshare audio only
* // val javaAudioDeviceModule = (room.lkObjects.audioDeviceModule as? JavaAudioDeviceModule)
* // javaAudioDeviceModule?.setAudioRecordEnabled(false)
*
* // Publish the audio track.
* room.localParticipant.setMicrophoneEnabled(true)
* val screenCaptureTrack = room.localParticipant.getTrackPublication(Track.Source.SCREEN_SHARE)?.track as? LocalVideoTrack ?: return
* val audioTrack = room.localParticipant.getTrackPublication(Track.Source.MICROPHONE)?.track as? LocalAudioTrack ?: return
*
* // Start capturing the screen share audio.
* val audioCapturer = ScreenAudioCapturer.createFromScreenShareTrack(screenCaptureTrack) ?: return
* audioCapturer.gain = 0.1f // Lower the volume so that mic can still be heard clearly.
* audioTrack.setAudioBufferCallback(audioCapturer)
* }
*
* suspend fun stopScreenCapture() {
* (room.localParticipant.getTrackPublication(Track.Source.MICROPHONE)?.track as? LocalAudioTrack)
* ?.setAudioBufferCallback(null)
* room.localParticipant.setMicrophoneEnabled(false)
* room.localParticipant.setScreenShareEnabled(false)
*
* // Remember to release when done capturing.
* audioCapturer?.releaseAudioResources()
* }
* ```
*/
@RequiresApi(Build.VERSION_CODES.Q)
class ScreenAudioCapturer
@RequiresPermission(Manifest.permission.RECORD_AUDIO)
constructor(
private val mediaProjection: MediaProjection,
/**
* Screen share audio capture requires the use of [AudioPlaybackCaptureConfiguration].
* This parameter allows customizing the configuration used. Note that
* the configuration must have at least one match rule applied to it or
* an exception will be thrown.
*
* The default configurator adds matching rules against all available usage
* types that can be captured.
*/
private val captureConfigurator: AudioPlaybackCaptureConfigurator = DEFAULT_CONFIGURATOR,
) : MixerAudioBufferCallback() {
private var audioRecord: AudioRecord? = null
private var hasInitialized = false
private var byteBuffer: ByteBuffer? = null
/**
* A multiplier to adjust the volume of the captured audio data.
*
* Values above 1 will increase the volume, values less than 1 will decrease it.
*/
var gain = DEFAULT_GAIN
override fun onBufferRequest(originalBuffer: ByteBuffer, audioFormat: Int, channelCount: Int, sampleRate: Int, bytesRead: Int, captureTimeNs: Long): BufferResponse? {
if (!hasInitialized && audioRecord == null) {
hasInitialized = true
initAudioRecord(audioFormat = audioFormat, channelCount = channelCount, sampleRate = sampleRate)
}
val audioRecord = this.audioRecord ?: return null
val recordBuffer = this.byteBuffer ?: return null
audioRecord.read(recordBuffer, recordBuffer.capacity())
if (abs(gain - DEFAULT_GAIN) > MIN_GAIN_CHANGE) {
recordBuffer.position(0)
when (audioFormat) {
AudioFormat.ENCODING_PCM_8BIT -> {
adjustByteBuffer(recordBuffer, gain)
}
AudioFormat.ENCODING_PCM_16BIT,
AudioFormat.ENCODING_DEFAULT,
-> {
adjustShortBuffer(recordBuffer.asShortBuffer(), gain)
}
AudioFormat.ENCODING_PCM_FLOAT -> {
adjustFloatBuffer(recordBuffer.asFloatBuffer(), gain)
}
else -> {
LKLog.w { "Unsupported audio format: $audioFormat" }
}
}
}
return BufferResponse(recordBuffer)
}
@SuppressLint("MissingPermission")
fun initAudioRecord(audioFormat: Int, channelCount: Int, sampleRate: Int): Boolean {
val audioCaptureConfig = AudioPlaybackCaptureConfiguration.Builder(mediaProjection)
.apply(captureConfigurator)
.build()
val channelMask = if (channelCount == 1) AudioFormat.CHANNEL_IN_MONO else AudioFormat.CHANNEL_IN_STEREO
val minBufferSize = AudioRecord.getMinBufferSize(sampleRate, channelMask, audioFormat)
if (minBufferSize == AudioRecord.ERROR || minBufferSize == AudioRecord.ERROR_BAD_VALUE) {
throw IllegalStateException("minBuffer size error: $minBufferSize")
}
LKLog.v { "AudioRecord.getMinBufferSize: $minBufferSize" }
val bytesPerFrame = channelCount * getBytesPerSample(audioFormat)
val framesPerBuffer = sampleRate / 100
val readBufferCapacity = bytesPerFrame * framesPerBuffer
val byteBuffer = ByteBuffer.allocateDirect(readBufferCapacity)
.order(ByteOrder.nativeOrder())
if (!byteBuffer.hasArray()) {
LKLog.e { "ByteBuffer does not have backing array." }
return false
}
this.byteBuffer = byteBuffer
val bufferSizeInBytes: Int = max(BUFFER_SIZE_FACTOR * minBufferSize, readBufferCapacity)
val audioRecord = AudioRecord.Builder()
.setAudioFormat(
AudioFormat.Builder()
.setEncoding(audioFormat)
.setSampleRate(sampleRate)
.setChannelMask(channelMask)
.build(),
)
.setBufferSizeInBytes(bufferSizeInBytes)
.setAudioPlaybackCaptureConfig(audioCaptureConfig)
.build()
try {
audioRecord.startRecording()
} catch (e: Exception) {
LKLog.e(e) { "AudioRecord.startRecording failed:" }
audioRecord.release()
return false
}
if (audioRecord.recordingState != AudioRecord.RECORDSTATE_RECORDING) {
LKLog.e {
"AudioRecord.startRecording failed - incorrect state: ${audioRecord.recordingState}"
}
return false
}
this.audioRecord = audioRecord
return true
}
/**
* Release any audio resources associated with this capturer.
* This is not managed by LiveKit, so you must call this function
* when finished to prevent memory leaks.
*/
fun releaseAudioResources() {
val audioRecord = this.audioRecord
if (audioRecord != null) {
audioRecord.release()
this.audioRecord = null
}
}
private fun getBytesPerSample(audioFormat: Int): Int {
return when (audioFormat) {
AudioFormat.ENCODING_PCM_8BIT -> 1
AudioFormat.ENCODING_PCM_16BIT, AudioFormat.ENCODING_IEC61937, AudioFormat.ENCODING_DEFAULT -> 2
AudioFormat.ENCODING_PCM_FLOAT -> 4
else -> throw IllegalArgumentException("Bad audio format $audioFormat")
}
}
companion object {
@RequiresPermission(Manifest.permission.RECORD_AUDIO)
fun createFromScreenShareTrack(track: Track?): ScreenAudioCapturer? {
val screenShareTrack = track as? LocalVideoTrack
if (screenShareTrack == null) {
LKLog.e { "Tried to create screen audio capturer but passed track is not a video track: $track" }
return null
}
val capturer = screenShareTrack.capturer as? ScreenCapturerAndroid
if (capturer == null) {
LKLog.e { "Tried to create screen audio capturer but passed track does not contain a screen capturer: ${screenShareTrack.capturer}" }
return null
}
val mediaProjection = capturer.mediaProjection
if (mediaProjection == null) {
LKLog.e { "Tried to create screen audio capturer but the capturer doesn't have a media projection. Have you called startCapture?" }
return null
}
return ScreenAudioCapturer(mediaProjection)
}
}
private fun adjustByteBuffer(
buffer: ByteBuffer,
gain: Float,
) {
for (i in 0 until buffer.capacity()) {
val adjusted = (buffer[i] * gain)
.roundToInt()
.coerceIn(Byte.MIN_VALUE.toInt(), Byte.MAX_VALUE.toInt())
buffer.put(i, adjusted.toByte())
}
}
private fun adjustShortBuffer(
buffer: ShortBuffer,
gain: Float,
) {
for (i in 0 until buffer.capacity()) {
val adjusted = (buffer[i] * gain)
.roundToInt()
.coerceIn(Short.MIN_VALUE.toInt(), Short.MAX_VALUE.toInt())
buffer.put(i, adjusted.toShort())
}
}
private fun adjustFloatBuffer(
buffer: FloatBuffer,
gain: Float,
) {
for (i in 0 until buffer.capacity()) {
val adjusted = (buffer[i] * gain)
.coerceIn(-1f, 1f)
buffer.put(i, adjusted)
}
}
}
typealias AudioPlaybackCaptureConfigurator = (AudioPlaybackCaptureConfiguration.Builder) -> Unit