@siteed/expo-audio-studio 2.10.6 → 2.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (23) hide show
  1. package/CHANGELOG.md +15 -1
  2. package/android/src/androidTest/java/net/siteed/audiostream/integration/AudioFocusStrategyIntegrationTest.kt +332 -0
  3. package/android/src/androidTest/java/net/siteed/audiostream/integration/DeviceDisconnectionFallbackTest.kt +218 -0
  4. package/android/src/androidTest/java/net/siteed/audiostream/integration/EventEmissionIntervalTest.kt +120 -0
  5. package/android/src/androidTest/java/net/siteed/audiostream/integration/M4aFormatTest.kt +345 -0
  6. package/android/src/androidTest/java/net/siteed/audiostream/integration/PcmStreamingDurationTest.kt +252 -0
  7. package/android/src/androidTest/java/net/siteed/audiostream/integration/run_integration_tests.sh +5 -0
  8. package/android/src/main/java/net/siteed/audiostream/AudioProcessor.kt +44 -32
  9. package/android/src/main/java/net/siteed/audiostream/AudioRecorderManager.kt +198 -22
  10. package/android/src/main/java/net/siteed/audiostream/RecordingConfig.kt +13 -4
  11. package/android/src/test/java/net/siteed/audiostream/AudioFocusStrategyTest.kt +249 -0
  12. package/android/src/test/java/net/siteed/audiostream/AudioFormatTest.kt +151 -0
  13. package/android/src/test/java/net/siteed/audiostream/DeviceDisconnectionFallbackUnitTest.kt +140 -0
  14. package/build/cjs/ExpoAudioStream.types.js.map +1 -1
  15. package/build/esm/ExpoAudioStream.types.js.map +1 -1
  16. package/build/types/ExpoAudioStream.types.d.ts +25 -2
  17. package/build/types/ExpoAudioStream.types.d.ts.map +1 -1
  18. package/ios/AudioStreamManager.swift +55 -43
  19. package/ios/ExpoAudioStudioTests/EventEmissionIntervalTests.swift +105 -0
  20. package/ios/tests/README.md +41 -0
  21. package/ios/tests/opus_support_test_macos.swift +154 -0
  22. package/package.json +2 -2
  23. package/src/ExpoAudioStream.types.ts +27 -2
@@ -0,0 +1,120 @@
1
+ package net.siteed.audiostream.integration
2
+
3
+ import android.os.Bundle
4
+ import android.util.Log
5
+ import androidx.test.ext.junit.runners.AndroidJUnit4
6
+ import androidx.test.platform.app.InstrumentationRegistry
7
+ import org.junit.Test
8
+ import org.junit.runner.RunWith
9
+ import org.junit.Assert.*
10
+ import java.io.File
11
+ import kotlin.math.abs
12
+
13
+ /**
14
+ * Integration test to validate event emission interval enforcement.
15
+ *
16
+ * This test verifies that the configured intervals respect platform
17
+ * minimums to prevent excessive CPU usage.
18
+ */
19
+ @RunWith(AndroidJUnit4::class)
20
+ class EventEmissionIntervalTest {
21
+
22
+ private val TAG = "EventEmissionIntervalTest"
23
+ private val context = InstrumentationRegistry.getInstrumentation().targetContext
24
+
25
+ @Test
26
+ fun testMinimumIntervalEnforcement() {
27
+ println("🧪 Test: Minimum Interval Enforcement")
28
+ println("------------------------------------")
29
+
30
+ // Test cases for different requested intervals
31
+ val testCases = listOf(
32
+ 5 to 10, // 5ms should be clamped to MIN_INTERVAL (10ms)
33
+ 10 to 10, // 10ms should remain 10ms
34
+ 50 to 50, // 50ms should remain 50ms
35
+ 100 to 100 // 100ms should remain 100ms
36
+ )
37
+
38
+ for ((requested, expected) in testCases) {
39
+ val config = Bundle().apply {
40
+ putInt("sampleRate", 48000)
41
+ putInt("channels", 1)
42
+ putLong("interval", requested.toLong())
43
+ putLong("intervalAnalysis", requested.toLong())
44
+ }
45
+
46
+ // Parse the config to validate interval enforcement
47
+ val configMap = bundleToMap(config)
48
+ val result = net.siteed.audiostream.RecordingConfig.fromMap(configMap)
49
+
50
+ assertTrue("Config parsing should succeed", result.isSuccess)
51
+ val (recordingConfig, _) = result.getOrNull()!!
52
+
53
+ println("Requested interval: ${requested}ms")
54
+ println("Actual interval: ${recordingConfig.interval}ms")
55
+ println("Expected interval: ${expected}ms")
56
+
57
+ assertEquals(
58
+ "Interval should be clamped to minimum if below MIN_INTERVAL",
59
+ expected.toLong(),
60
+ recordingConfig.interval
61
+ )
62
+
63
+ assertEquals(
64
+ "Analysis interval should be clamped to minimum if below MIN_INTERVAL",
65
+ expected.toLong(),
66
+ recordingConfig.intervalAnalysis
67
+ )
68
+
69
+ println("✓ Passed\n")
70
+ }
71
+ }
72
+
73
+ @Test
74
+ fun testIntervalConsistencyAcrossPlatforms() {
75
+ println("🧪 Test: Platform Consistency Check")
76
+ println("----------------------------------")
77
+
78
+ // Document the expected behavior across platforms
79
+ println("Expected behavior after fix:")
80
+ println("- iOS: Minimum interval = 10ms")
81
+ println("- Android: Minimum interval = 10ms (enforced)")
82
+ println("")
83
+
84
+ // Verify Android enforces the minimum
85
+ val intervals = listOf(1, 5, 10, 50, 100)
86
+ for (interval in intervals) {
87
+ val config = Bundle().apply {
88
+ putLong("interval", interval.toLong())
89
+ putLong("intervalAnalysis", interval.toLong())
90
+ }
91
+
92
+ val configMap = bundleToMap(config)
93
+ val result = net.siteed.audiostream.RecordingConfig.fromMap(configMap)
94
+ val (recordingConfig, _) = result.getOrNull()!!
95
+
96
+ val expectedInterval = maxOf(10, interval).toLong()
97
+ assertEquals(
98
+ "Android should enforce MIN_INTERVAL of 10ms",
99
+ expectedInterval,
100
+ recordingConfig.interval
101
+ )
102
+
103
+ println("✓ Interval ${interval}ms -> ${recordingConfig.interval}ms")
104
+ }
105
+ }
106
+
107
+ /**
108
+ * Helper to convert Bundle to Map for RecordingConfig
109
+ */
110
+ private fun bundleToMap(bundle: Bundle): Map<String, Any?> {
111
+ val map = mutableMapOf<String, Any?>()
112
+ for (key in bundle.keySet()) {
113
+ when (val value = bundle.get(key)) {
114
+ is Bundle -> map[key] = bundleToMap(value)
115
+ else -> map[key] = value
116
+ }
117
+ }
118
+ return map
119
+ }
120
+ }
@@ -0,0 +1,345 @@
1
+ package net.siteed.audiostream.integration
2
+
3
+ import android.Manifest
4
+ import android.content.Context
5
+ import android.media.MediaExtractor
6
+ import android.media.MediaFormat
7
+ import androidx.test.ext.junit.runners.AndroidJUnit4
8
+ import androidx.test.platform.app.InstrumentationRegistry
9
+ import androidx.test.rule.GrantPermissionRule
10
+ import expo.modules.kotlin.Promise
11
+ import net.siteed.audiostream.*
12
+ import org.junit.After
13
+ import org.junit.Assert.*
14
+ import org.junit.Before
15
+ import org.junit.Rule
16
+ import org.junit.Test
17
+ import org.junit.runner.RunWith
18
+ import java.io.File
19
+ import java.util.concurrent.CountDownLatch
20
+ import java.util.concurrent.TimeUnit
21
+
22
+ @RunWith(AndroidJUnit4::class)
23
+ class M4aFormatTest {
24
+
25
+ @get:Rule
26
+ val grantPermissionRule: GrantPermissionRule = GrantPermissionRule.grant(
27
+ Manifest.permission.RECORD_AUDIO
28
+ )
29
+
30
+ private lateinit var context: Context
31
+ private lateinit var filesDir: File
32
+ private lateinit var audioRecorderManager: AudioRecorderManager
33
+ private lateinit var testEventSender: TestEventSender
34
+ private lateinit var permissionUtils: PermissionUtils
35
+ private lateinit var audioDataEncoder: AudioDataEncoder
36
+
37
+ // Test event sender to capture events
38
+ private class TestEventSender : EventSender {
39
+ override fun sendExpoEvent(eventName: String, params: android.os.Bundle) {
40
+ // No-op for tests
41
+ }
42
+ }
43
+
44
+ @Before
45
+ fun setUp() {
46
+ context = InstrumentationRegistry.getInstrumentation().targetContext
47
+ filesDir = context.filesDir
48
+ testEventSender = TestEventSender()
49
+ permissionUtils = PermissionUtils(context)
50
+ audioDataEncoder = AudioDataEncoder()
51
+
52
+ // Initialize AudioRecorderManager
53
+ audioRecorderManager = AudioRecorderManager.initialize(
54
+ context = context,
55
+ filesDir = filesDir,
56
+ permissionUtils = permissionUtils,
57
+ audioDataEncoder = audioDataEncoder,
58
+ eventSender = testEventSender,
59
+ enablePhoneStateHandling = false,
60
+ enableBackgroundAudio = false
61
+ )
62
+
63
+ // Clean up any existing audio files
64
+ cleanupAudioFiles()
65
+ }
66
+
67
+ @After
68
+ fun tearDown() {
69
+ // Stop any ongoing recording
70
+ if (audioRecorderManager.isRecording) {
71
+ stopRecordingSync()
72
+ }
73
+
74
+ // Clean up
75
+ AudioRecorderManager.destroy()
76
+ cleanupAudioFiles()
77
+ }
78
+
79
+ private fun cleanupAudioFiles() {
80
+ filesDir.listFiles()?.forEach { file ->
81
+ if (file.name.endsWith(".wav") || file.name.endsWith(".aac") ||
82
+ file.name.endsWith(".m4a") || file.name.endsWith(".opus")) {
83
+ file.delete()
84
+ }
85
+ }
86
+ }
87
+
88
+ @Test
89
+ fun testAacFormat_producesM4aByDefault() {
90
+ // Skip test if API level is too low for compressed recording
91
+ if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.Q) {
92
+ println("Skipping M4A test - requires API 29+, current API: ${android.os.Build.VERSION.SDK_INT}")
93
+ return
94
+ }
95
+
96
+ // Given
97
+ val recordingOptions = mapOf(
98
+ "sampleRate" to 44100,
99
+ "channels" to 1,
100
+ "encoding" to "pcm_16bit",
101
+ "interval" to 100,
102
+ "showNotification" to false,
103
+ "output" to mapOf(
104
+ "primary" to mapOf("enabled" to false),
105
+ "compressed" to mapOf(
106
+ "enabled" to true,
107
+ "format" to "aac"
108
+ // preferRawStream not specified = defaults to false = M4A
109
+ )
110
+ )
111
+ )
112
+
113
+ // When - Record for 1 second
114
+ startRecordingSync(recordingOptions)
115
+ Thread.sleep(1000)
116
+ val result = stopRecordingSync()
117
+
118
+ // Then
119
+ val compression = when (val comp = result["compression"]) {
120
+ is android.os.Bundle -> bundleToMap(comp)
121
+ is Map<*, *> -> comp
122
+ else -> null
123
+ }
124
+
125
+ val compressedUri = compression?.get("compressedFileUri") as? String
126
+ assertNotNull("Compressed file URI should not be null", compressedUri)
127
+
128
+ val file = when {
129
+ compressedUri!!.startsWith("file://") -> File(java.net.URI(compressedUri))
130
+ compressedUri.startsWith("file:") -> File(java.net.URI(compressedUri))
131
+ else -> File(compressedUri)
132
+ }
133
+
134
+ assertTrue("File should exist", file.exists())
135
+ assertTrue("File should have .m4a extension", file.name.endsWith(".m4a"))
136
+
137
+ // Verify it's actually an M4A file
138
+ verifyM4aFormat(file)
139
+ }
140
+
141
+ @Test
142
+ fun testAacFormat_withPreferRawStream_producesAac() {
143
+ // Skip test if API level is too low for compressed recording
144
+ if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.Q) {
145
+ println("Skipping raw AAC test - requires API 29+, current API: ${android.os.Build.VERSION.SDK_INT}")
146
+ return
147
+ }
148
+
149
+ // Given
150
+ val recordingOptions = mapOf(
151
+ "sampleRate" to 44100,
152
+ "channels" to 1,
153
+ "encoding" to "pcm_16bit",
154
+ "interval" to 100,
155
+ "showNotification" to false,
156
+ "output" to mapOf(
157
+ "primary" to mapOf("enabled" to false),
158
+ "compressed" to mapOf(
159
+ "enabled" to true,
160
+ "format" to "aac",
161
+ "preferRawStream" to true // NEW: Request raw AAC stream
162
+ )
163
+ )
164
+ )
165
+
166
+ // When - Record for 1 second
167
+ startRecordingSync(recordingOptions)
168
+ Thread.sleep(1000)
169
+ val result = stopRecordingSync()
170
+
171
+ // Then
172
+ val compression = when (val comp = result["compression"]) {
173
+ is android.os.Bundle -> bundleToMap(comp)
174
+ is Map<*, *> -> comp
175
+ else -> null
176
+ }
177
+
178
+ val compressedUri = compression?.get("compressedFileUri") as? String
179
+ assertNotNull("Compressed file URI should not be null", compressedUri)
180
+
181
+ val file = when {
182
+ compressedUri!!.startsWith("file://") -> File(java.net.URI(compressedUri))
183
+ compressedUri.startsWith("file:") -> File(java.net.URI(compressedUri))
184
+ else -> File(compressedUri)
185
+ }
186
+
187
+ assertTrue("File should exist", file.exists())
188
+ assertTrue("File should have .aac extension", file.name.endsWith(".aac"))
189
+
190
+ // Verify it's actually an AAC ADTS file
191
+ verifyAacAdtsFormat(file)
192
+ }
193
+
194
+ @Test
195
+ fun testOpusFormat_producesOpus() {
196
+ // Skip test if API level is too low for Opus recording
197
+ if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.Q) {
198
+ println("Skipping Opus test - requires API 29+, current API: ${android.os.Build.VERSION.SDK_INT}")
199
+ return
200
+ }
201
+
202
+ // Given
203
+ val recordingOptions = mapOf(
204
+ "sampleRate" to 48000,
205
+ "channels" to 1,
206
+ "encoding" to "pcm_16bit",
207
+ "interval" to 100,
208
+ "showNotification" to false,
209
+ "output" to mapOf(
210
+ "primary" to mapOf("enabled" to false),
211
+ "compressed" to mapOf(
212
+ "enabled" to true,
213
+ "format" to "opus"
214
+ )
215
+ )
216
+ )
217
+
218
+ // When - Record for 1 second
219
+ startRecordingSync(recordingOptions)
220
+ Thread.sleep(1000)
221
+ val result = stopRecordingSync()
222
+
223
+ // Then
224
+ val compression = when (val comp = result["compression"]) {
225
+ is android.os.Bundle -> bundleToMap(comp)
226
+ is Map<*, *> -> comp
227
+ else -> null
228
+ }
229
+
230
+ val compressedUri = compression?.get("compressedFileUri") as? String
231
+ assertNotNull("Compressed file URI should not be null", compressedUri)
232
+
233
+ val file = when {
234
+ compressedUri!!.startsWith("file://") -> File(java.net.URI(compressedUri))
235
+ compressedUri.startsWith("file:") -> File(java.net.URI(compressedUri))
236
+ else -> File(compressedUri)
237
+ }
238
+
239
+ assertTrue("File should exist", file.exists())
240
+ assertTrue("File should have .opus extension", file.name.endsWith(".opus"))
241
+ }
242
+
243
+ // Helper methods from existing tests
244
+ private fun startRecordingSync(recordingOptions: Map<String, Any?>): Map<String, Any?> {
245
+ val startLatch = CountDownLatch(1)
246
+ var recordingResult: Map<String, Any?>? = null
247
+
248
+ audioRecorderManager.startRecording(recordingOptions, object : Promise {
249
+ override fun resolve(value: Any?) {
250
+ when (value) {
251
+ is android.os.Bundle -> recordingResult = bundleToMap(value)
252
+ is Map<*, *> -> {
253
+ @Suppress("UNCHECKED_CAST")
254
+ recordingResult = value as? Map<String, Any>
255
+ }
256
+ else -> {
257
+ fail("Unexpected start result type: ${value?.javaClass?.name}")
258
+ }
259
+ }
260
+ startLatch.countDown()
261
+ }
262
+
263
+ override fun reject(code: String, message: String?, cause: Throwable?) {
264
+ fail("Recording start failed: $code - $message")
265
+ }
266
+ })
267
+
268
+ assertTrue("Recording should start within 2 seconds", startLatch.await(2, TimeUnit.SECONDS))
269
+ return recordingResult ?: throw AssertionError("Recording result should not be null")
270
+ }
271
+
272
+ private fun stopRecordingSync(): Map<String, Any?> {
273
+ val stopLatch = CountDownLatch(1)
274
+ var stopResult: Map<String, Any?>? = null
275
+
276
+ audioRecorderManager.stopRecording(object : Promise {
277
+ override fun resolve(value: Any?) {
278
+ when (value) {
279
+ is android.os.Bundle -> stopResult = bundleToMap(value)
280
+ is Map<*, *> -> {
281
+ @Suppress("UNCHECKED_CAST")
282
+ stopResult = value as? Map<String, Any>
283
+ }
284
+ else -> {
285
+ fail("Unexpected stop result type: ${value?.javaClass?.name}")
286
+ }
287
+ }
288
+ stopLatch.countDown()
289
+ }
290
+
291
+ override fun reject(code: String, message: String?, cause: Throwable?) {
292
+ fail("Recording stop failed: $code - $message")
293
+ }
294
+ })
295
+
296
+ assertTrue("Recording should stop within 2 seconds", stopLatch.await(2, TimeUnit.SECONDS))
297
+ return stopResult ?: throw AssertionError("Stop result should not be null")
298
+ }
299
+
300
+ private fun bundleToMap(bundle: android.os.Bundle): Map<String, Any?> {
301
+ val map = mutableMapOf<String, Any?>()
302
+ for (key in bundle.keySet()) {
303
+ map[key] = bundle.get(key)
304
+ }
305
+ return map
306
+ }
307
+
308
+ private fun verifyM4aFormat(file: File) {
309
+ val extractor = MediaExtractor()
310
+ try {
311
+ extractor.setDataSource(file.absolutePath)
312
+ assertTrue("Should have at least one track", extractor.trackCount > 0)
313
+
314
+ val format = extractor.getTrackFormat(0)
315
+ val mimeType = format.getString(MediaFormat.KEY_MIME)
316
+
317
+ // Debug output
318
+ println("Detected MIME type: $mimeType")
319
+
320
+ // For M4A files, the MIME type should be audio/mp4 or contain aac
321
+ val isValidM4aMimeType = mimeType?.let { mime ->
322
+ mime.contains("mp4", ignoreCase = true) ||
323
+ mime.contains("aac", ignoreCase = true) ||
324
+ mime.contains("audio/", ignoreCase = true)
325
+ } ?: false
326
+
327
+ assertTrue("MIME type should be valid for M4A format, got: $mimeType", isValidM4aMimeType)
328
+
329
+ // Read file header to verify MP4 container
330
+ val header = file.inputStream().use { it.readNBytes(20) }
331
+ val headerString = String(header, Charsets.ISO_8859_1)
332
+ val hasFtyp = headerString.contains("ftyp")
333
+ assertTrue("File should contain ftyp box (MP4 container)", hasFtyp)
334
+ } finally {
335
+ extractor.release()
336
+ }
337
+ }
338
+
339
+ private fun verifyAacAdtsFormat(file: File) {
340
+ // ADTS header starts with 0xFFF
341
+ val header = file.inputStream().use { it.readNBytes(2) }
342
+ val syncWord = ((header[0].toInt() and 0xFF) shl 4) or ((header[1].toInt() and 0xF0) shr 4)
343
+ assertEquals("ADTS sync word should be 0xFFF", 0xFFF, syncWord)
344
+ }
345
+ }