@simba-dev/react-native-media-player 2.0.0 → 2.1.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 (39) hide show
  1. package/README.md +317 -560
  2. package/android/src/main/cpp/main.cpp +117 -17
  3. package/android/src/main/java/com/simba/player/PipManager.kt +13 -0
  4. package/android/src/main/java/com/simba/player/mpv/MpvBridgeModule.kt +187 -8
  5. package/android/src/main/java/com/simba/player/mpv/MpvRenderViewManager.kt +11 -1
  6. package/android/src/main/java/com/simba/player/mpv/MpvRenderViewRegistry.kt +132 -0
  7. package/android/src/main/java/com/simba/player/mpv/PipAutoEnterPolicy.kt +54 -0
  8. package/android/src/main/java/com/simba/player/mpv/PlayerSurface.kt +41 -1
  9. package/package.json +11 -2
  10. package/src/bridge/MpvPlayerModule.ts +7 -1
  11. package/src/bridge/NativeMpvPlayer.ts +3 -3
  12. package/src/types/player.ts +7 -1
  13. package/android/src/test/java/com/simba/player/PipActionReceiverTest.kt +0 -123
  14. package/android/src/test/java/com/simba/player/PipManagerTest.kt +0 -281
  15. package/android/src/test/java/com/simba/player/TestApplication.kt +0 -26
  16. package/android/src/test/java/com/simba/player/mpv/MpvBridgeModuleNullInstanceTest.kt +0 -117
  17. package/android/src/test/java/com/simba/player/mpv/MpvBridgeModuleTest.kt +0 -212
  18. package/android/src/test/java/com/simba/player/mpv/MpvRenderViewTest.kt +0 -249
  19. package/scripts/override_react_methods.js +0 -184
  20. package/scripts/override_react_methods.py +0 -150
  21. package/src/bridge/__tests__/MpvPlayerModule.test.ts +0 -110
  22. package/src/bridge/__tests__/debugMode.test.ts +0 -138
  23. package/src/bridge/__tests__/errorContract.test.ts +0 -175
  24. package/src/bridge/__tests__/loadAndPlay.startPosition.test.tsx +0 -142
  25. package/src/components/__tests__/PlayerProvider.performance.test.tsx +0 -242
  26. package/src/components/__tests__/PlayerProvider.progressContext.test.tsx +0 -194
  27. package/src/components/__tests__/PlayerProvider.test.tsx +0 -558
  28. package/src/components/__tests__/PlayerRoot.test.tsx +0 -71
  29. package/src/components/__tests__/SimbaVideo.test.tsx +0 -164
  30. package/src/hooks/__tests__/resolveStreamType.test.ts +0 -159
  31. package/src/hooks/__tests__/useLaunchPlayback.test.tsx +0 -278
  32. package/src/hooks/__tests__/useResumeThumbnail.test.ts +0 -154
  33. package/src/stores/__tests__/playerQueueSelectionStore.test.ts +0 -73
  34. package/src/stores/__tests__/playerQueueStore.test.ts +0 -171
  35. package/src/types/__tests__/config.test.ts +0 -188
  36. package/src/types/__tests__/player.pipAnswer.test.tsx +0 -87
  37. package/src/types/__tests__/player.pipArity.test.tsx +0 -74
  38. package/src/types/__tests__/player.test.tsx +0 -1365
  39. package/src/types/__tests__/playerLoading.test.ts +0 -170
@@ -1,249 +0,0 @@
1
- package com.simba.player.mpv
2
-
3
- import android.os.Build
4
- import android.view.Surface
5
- import android.view.ViewGroup
6
- import androidx.test.core.app.ApplicationProvider
7
- import androidx.test.ext.junit.runners.AndroidJUnit4
8
- import com.simba.player.TestApplication
9
- import org.junit.Assert.assertEquals
10
- import org.junit.Assert.assertNotNull
11
- import org.junit.Assert.assertNull
12
- import org.junit.Before
13
- import org.junit.Ignore
14
- import org.junit.Test
15
- import org.junit.runner.RunWith
16
- import org.mockito.kotlin.mock
17
- import org.robolectric.annotation.Config
18
-
19
- /**
20
- * Unit tests for [MpvRenderView]'s private surface attach/detach
21
- * machinery, covering V12 spec §Phase 33.5 (null surface guard) and
22
- * §Phase 33.6 (detach idempotency).
23
- *
24
- * Both methods are `private` and interact with [MPVLib] (a JNI wrapper
25
- * that requires `System.loadLibrary("simbaplayer_mpv")` — not available
26
- * in JVM unit tests). We use reflection to:
27
- * 1. invoke the private methods directly with crafted inputs
28
- * 2. read/write the private `nativePtr` and `attachedSurface` fields
29
- * to drive specific branches
30
- *
31
- * What we test:
32
- * - attachSurfaceLocked(null) is a no-op (Phase 33.5) — added as a
33
- * defensive guard in Phase 33.
34
- * - attachSurfaceLocked with `nativePtr == 0L` is a no-op (covers the
35
- * "mpv not initialized yet" cold-start case).
36
- * - attachSurfaceLocked is idempotent for the same Surface instance
37
- * (the `attachedSurface === surface` check).
38
- * - detachSurfaceLocked is idempotent (Phase 33.6) — multiple calls
39
- * with `attachedSurface == null` don't crash.
40
- * - detachSurfaceLocked with `nativePtr == 0L` is a no-op.
41
- * - cleanup() (the public entry-point for "mpv destroyed") is safe
42
- * to call multiple times.
43
- * - surfaceCreated / surfaceDestroyed callbacks (the public API path
44
- * that drives attach/detach internally) work without crashing.
45
- *
46
- * Why Robolectric + AndroidJUnit4:
47
- * - `View.isAttachedToWindow()` works under Robolectric (returns false
48
- * because no Activity host has attached the view). This means the
49
- * attachSurfaceLocked's `!isAttachedToWindow` early-return is
50
- * always taken in unit tests — which is exactly what we want to
51
- * verify for the audio-mode / GONE case.
52
- * - `Surface` and `SurfaceHolder` can be mocked via Mockito.
53
- *
54
- * **Sandboxed CI runner limitation:** Robolectric downloads the
55
- * `android-all-instrumented` runtime jar from Maven Central at first
56
- * run. Sandboxed environments that block writes to `~/.m2/repository/`
57
- * (notably the TRAE sandbox) cannot populate the cache. The whole
58
- * class is `@Ignore`'d; CI runners with full disk access can run the
59
- * suite.
60
- */
61
- @Ignore("Robolectric requires downloading android-all-instrumented jars at first run; sandboxed CI runners block writes to ~/.m2/repository/. Run on a non-sandboxed workstation or full CI runner to enable.")
62
- @RunWith(AndroidJUnit4::class)
63
- @Config(sdk = [Build.VERSION_CODES.TIRAMISU], application = TestApplication::class)
64
- class MpvRenderViewTest {
65
-
66
- private lateinit var view: MpvRenderView
67
-
68
- private val nativePtrField by lazy {
69
- MpvRenderView::class.java
70
- .getDeclaredField("nativePtr")
71
- .apply { isAccessible = true }
72
- }
73
-
74
- private val attachedSurfaceField by lazy {
75
- MpvRenderView::class.java
76
- .getDeclaredField("attachedSurface")
77
- .apply { isAccessible = true }
78
- }
79
-
80
- private val attachSurfaceLockedMethod by lazy {
81
- MpvRenderView::class.java
82
- .getDeclaredMethod("attachSurfaceLocked", Surface::class.java)
83
- .apply { isAccessible = true }
84
- }
85
-
86
- private val detachSurfaceLockedMethod by lazy {
87
- MpvRenderView::class.java
88
- .getDeclaredMethod("detachSurfaceLocked")
89
- .apply { isAccessible = true }
90
- }
91
-
92
- @Before
93
- fun setUp() {
94
- view = MpvRenderView(ApplicationProvider.getApplicationContext())
95
- }
96
-
97
- // ── Spec §Phase 33.5: null surface is a no-op ────────────────────────
98
-
99
- @Test
100
- fun attachSurfaceLocked_nullSurface_isNoOp() {
101
- // Phase 33.5: the method must not NPE when called with a null
102
- // Surface. The new guard `if (surface == null) return` catches
103
- // this BEFORE the `surface.isValid` deref.
104
- // Set nativePtr to a non-zero value so the null guard is the
105
- // active check (rather than the earlier `nativePtr == 0L` guard).
106
- nativePtrField.setLong(view, 1L)
107
- // The actual reflection invocation must complete without
108
- // throwing. If the null guard is missing, this NPEs on
109
- // `surface.isValid`.
110
- attachSurfaceLockedMethod.invoke(view, /* surface = */ null)
111
- // Sanity: nativePtr is unchanged (the guard returned before any
112
- // mpv interaction).
113
- assertEquals(1L, nativePtrField.getLong(view))
114
- }
115
-
116
- @Test
117
- fun attachSurfaceLocked_nativePtrZero_isNoOp() {
118
- // Cold-start path: mpv not yet initialized (nativePtr == 0L).
119
- // The first guard `if (nativePtr == 0L) return` catches this
120
- // before any surface check.
121
- nativePtrField.setLong(view, 0L)
122
- // A non-null surface is required to confirm the guard is
123
- // checking nativePtr, not surface. (A mock Surface would NPE on
124
- // isValid, but we won't reach that line.)
125
- val mockSurface = mock<Surface>()
126
- attachSurfaceLockedMethod.invoke(view, mockSurface)
127
- assertEquals(0L, nativePtrField.getLong(view))
128
- }
129
-
130
- @Test
131
- fun attachSurfaceLocked_nullSurfaceAndNativePtrZero_isNoOp() {
132
- // Combined path: both guards trigger, but the earlier one wins.
133
- nativePtrField.setLong(view, 0L)
134
- attachSurfaceLockedMethod.invoke(view, null)
135
- assertEquals(0L, nativePtrField.getLong(view))
136
- }
137
-
138
- // ── Spec §Phase 33.6: detachSurfaceLocked idempotency ────────────────
139
-
140
- @Test
141
- fun detachSurfaceLocked_nativePtrZero_isNoOp() {
142
- // The method's first guard is `if (nativePtr == 0L) return;`.
143
- // Calling it on a fresh view (no mpv yet) must be a no-op.
144
- nativePtrField.setLong(view, 0L)
145
- detachSurfaceLockedMethod.invoke(view)
146
- detachSurfaceLockedMethod.invoke(view)
147
- detachSurfaceLockedMethod.invoke(view)
148
- // No exception thrown + nativePtr still 0.
149
- assertEquals(0L, nativePtrField.getLong(view))
150
- assertNull(attachedSurfaceField.get(view))
151
- }
152
-
153
- @Test
154
- fun detachSurfaceLocked_attachedSurfaceAlreadyNull_isNoOp() {
155
- // Second guard: `if (attachedSurface == null) return;`. With
156
- // nativePtr non-zero but no attached surface, calling detach
157
- // must be a no-op (and not accidentally call MPVLib).
158
- nativePtrField.setLong(view, 1L)
159
- attachedSurfaceField.set(view, null)
160
- detachSurfaceLockedMethod.invoke(view)
161
- detachSurfaceLockedMethod.invoke(view)
162
- // Native ptr unchanged (detach returned early).
163
- assertEquals(1L, nativePtrField.getLong(view))
164
- assertNull(attachedSurfaceField.get(view))
165
- }
166
-
167
- @Test
168
- fun cleanup_isIdempotent_andSafeToCallMultipleTimes() {
169
- // The public cleanup() entry-point delegates to
170
- // detachSurfaceLocked() and zeros nativePtr. It should be safe
171
- // to call multiple times (e.g. if onDestroy fires twice due to
172
- // some Activity restart edge case).
173
- view.cleanup()
174
- view.cleanup()
175
- view.cleanup()
176
- // After cleanup: nativePtr is 0 and attachedSurface is null.
177
- assertEquals(0L, nativePtrField.getLong(view))
178
- assertNull(attachedSurfaceField.get(view))
179
- }
180
-
181
- // ── SurfaceHolder.Callback (public API) ──────────────────────────────
182
-
183
- @Test
184
- fun surfaceDestroyed_withAttachedSurface_resetsState() {
185
- // Verify the public surfaceDestroyed path calls
186
- // detachSurfaceLocked which guards on attachedSurface == null.
187
- // We start with nativePtr=0, so detach should be a no-op.
188
- nativePtrField.setLong(view, 0L)
189
- view.surfaceDestroyed(view.holder)
190
- // If we got here without exception, the callback path is safe.
191
- assertEquals(0L, nativePtrField.getLong(view))
192
- }
193
-
194
- @Test
195
- fun surfaceCreated_doesNotCrash_whenMpvNotInitialized() {
196
- // Verify the public surfaceCreated path calls
197
- // attachSurfaceLocked(holder.surface). With nativePtr=0, the
198
- // early-return prevents any JNI access. holder.surface may be
199
- // null under Robolectric (no real Surface backing), which
200
- // tests our null guard transitively.
201
- nativePtrField.setLong(view, 0L)
202
- view.surfaceCreated(view.holder)
203
- assertEquals(0L, nativePtrField.getLong(view))
204
- }
205
-
206
- // ── Lifecycle: cleanup resets state correctly ────────────────────────
207
-
208
- @Test
209
- fun cleanup_afterAttachAttempt_resetsNativePtr() {
210
- // Simulate an attach attempt that did happen (attachedSurface
211
- // non-null) and then cleanup. Cleanup zeros nativePtr.
212
- nativePtrField.setLong(view, 1L)
213
- val mockSurface = mock<Surface>()
214
- attachedSurfaceField.set(view, mockSurface)
215
- view.cleanup()
216
- assertEquals(0L, nativePtrField.getLong(view))
217
- // detachSurfaceLocked sets attachedSurface = null (the line
218
- // runs BEFORE we zero nativePtr in cleanup()).
219
- assertNull(attachedSurfaceField.get(view))
220
- }
221
-
222
- // ── Layout params sanity ──────────────────────────────────────────────
223
-
224
- @Test
225
- fun init_setsMatchParentLayoutParams() {
226
- // The view's layoutParams are set in init to MATCH_PARENT x
227
- // MATCH_PARENT. This is part of the SurfaceView contract
228
- // required for PiP — verify it's not regressed.
229
- assertNotNull(view.layoutParams)
230
- assertEquals(
231
- ViewGroup.LayoutParams.MATCH_PARENT,
232
- view.layoutParams.width,
233
- )
234
- assertEquals(
235
- ViewGroup.LayoutParams.MATCH_PARENT,
236
- view.layoutParams.height,
237
- )
238
- }
239
-
240
- @Test
241
- fun init_setsNonInteractiveFlags() {
242
- // SurfaceView itself shouldn't capture touches — the controls
243
- // overlay handles them. isFocusable=false + isClickable=false
244
- // prevent the SurfaceView from stealing focus when overlays
245
- // are added on top.
246
- assertEquals(false, view.isFocusable)
247
- assertEquals(false, view.isClickable)
248
- }
249
- }
@@ -1,184 +0,0 @@
1
- #!/usr/bin/env node
2
- /**
3
- * V16.0.6 patch release (D-032 / B-010 proper fix):
4
- * MpvBridgeModule.kt must extend NativeMpvPlayerSpec. Every @ReactMethod-
5
- * annotated function is an override of the spec's abstract method, so we add
6
- * `@Override` (Kotlin annotation) on its own line and the `override` keyword
7
- * on the `fun` line.
8
- *
9
- * We also normalize a handful of signature mismatches:
10
- * - dumpObservedProperties(): Int → Double (spec returns double)
11
- * - openPlayer(..., title: String?, ...): Promise
12
- * → title: String (spec is non-null)
13
- * - enterPip(chapterTitle: String? = null, progressPct: String? = null)
14
- * → enterPip(chapterTitle: String, progressPct: String)
15
- * (spec is non-null, no defaults; defaults are dropped — the only
16
- * internal callers were JS via @ReactMethod)
17
- *
18
- * Methods NOT in the spec (addListener / removeListeners / startNotification
19
- * / updateNotification / stopNotification / initialize lifecycle / the
20
- * IMpvConfigProvider & IMpvNativePtrProvider & IPipModeChangeEmitter
21
- * implementations) are left untouched so they keep their RN-bridge / private
22
- * implementor semantics.
23
- *
24
- * The toggleMute() stub is added in a separate pass — the spec declares
25
- * `abstract void toggleMute();` but MpvBridgeModule.kt 1.5.5 doesn't have
26
- * the Kotlin override, so extending NativeMpvPlayerSpec would otherwise
27
- * fail to compile with the dreaded
28
- * "Class 'MpvBridgeModule' is not abstract and does not override abstract
29
- * member 'public abstract void toggleMute()'".
30
- */
31
- "use strict";
32
-
33
- const fs = require("fs");
34
- const path = require("path");
35
-
36
- const SRC_PATH = path.resolve(
37
- "X:/Development/SIMBA/react-native-media-player/android/src/main/java/" +
38
- "com/simba/player/mpv/MpvBridgeModule.kt"
39
- );
40
-
41
- // @ReactMethod-annotated methods on MpvBridgeModule that are NOT in the
42
- // NativeMpvPlayerSpec — we must NOT add `override` to them.
43
- const NON_SPEC_REACT_METHODS = new Set([
44
- "addListener", // RN NativeEventEmitter requirement
45
- "removeListeners", // RN NativeEventEmitter requirement
46
- "startNotification", // lib-private notification flow
47
- "updateNotification",// lib-private notification flow
48
- "stopNotification", // lib-private notification flow
49
- ]);
50
-
51
- // Exact signature normalizations to apply BEFORE the @Override pass so
52
- // capture groups line up with existing line breaks.
53
- const SIGNATURE_NORMALIZATIONS = [
54
- // 1. dumpObservedProperties(): Int -> Double (spec returns double)
55
- {
56
- name: "dumpObservedProperties-return-type",
57
- pattern: /( @ReactMethod\(isBlockingSynchronousMethod = true\)\r?\n fun dumpObservedProperties)\(\): Int \{/,
58
- replacement: "$1(): Double {",
59
- },
60
- // 2. openPlayer title: String? -> String
61
- {
62
- name: "openPlayer-title-type",
63
- pattern: /( fun openPlayer\(\r?\n uri: String,\r?\n) title: String\?,\r?\n/,
64
- replacement: "$1 title: String,\r\n",
65
- },
66
- // 2b. openPlayer body — title?.takeIf { ... } -> title.takeIf { ... }
67
- {
68
- name: "openPlayer-body-takeif",
69
- pattern: / val resolvedTitle = title\?\.takeIf \{ it\.isNotBlank\(\) \} \?: uri/,
70
- replacement: " val resolvedTitle = title.takeIf { it.isNotBlank() } ?: uri",
71
- },
72
- // 3. enterPip — v1.9.3: THE NORMALIZATION IS GONE.
73
- //
74
- // It used to rewrite
75
- // fun enterPip(chapterTitle: String? = null, progressPct: String? = null)
76
- // into
77
- // fun enterPip(chapterTitle: String, progressPct: String)
78
- // on the stated grounds that "the spec is non-null, no defaults".
79
- //
80
- // That was the cause of a hard crash, not a compatibility fix.
81
- // TurboModule enforces the KOTLIN arity, and the TypeScript contract
82
- // has always declared both params optional, so `enterPip()` from JS
83
- // was rejected before it reached the method body:
84
- //
85
- // Exception in HostFunction: TurboModule method "enterPip"
86
- // called with 0 arguments (expected argument count: 2)
87
- //
88
- // The nullability is now KEPT (that is what codegen produces from
89
- // `MpvPlayerModule.ts`), which makes both zero-arg and two-arg calls
90
- // legal. This rule used to throw if it matched zero times, so it
91
- // could not simply be left in place: re-running this script would
92
- // have failed the build with a confusing "did not match exactly once"
93
- // rather than silently reverting the fix. Kept here as an
94
- // assertion instead, so a re-run PROVES the signature is still the
95
- // fixed one and fails loudly if someone reintroduces the bug.
96
- {
97
- name: "enterPip-signature-guard",
98
- pattern: / override fun enterPip\(chapterTitle: String\?, progressPct: String\?\) \{/,
99
- replacement: " override fun enterPip(chapterTitle: String?, progressPct: String?) {",
100
- },
101
- ];
102
-
103
- const REACT_METHOD_LINE = /^( )(@ReactMethod(?:\([^)]*\))?)\s*$/;
104
- const FUN_LINE = /^( )fun ([A-Za-z_][A-Za-z0-9_]*)(\(.*)$/;
105
-
106
- function applySignatureNormalizations(src) {
107
- for (const norm of SIGNATURE_NORMALIZATIONS) {
108
- // Count non-overlapping matches via the `g` + `exec` loop (reliable even
109
- // when the regex has capture groups — `String.prototype.split` would
110
- // inflate its count by the number of captures).
111
- const re = new RegExp(norm.pattern.source, "g");
112
- let count = 0;
113
- let m;
114
- while ((m = re.exec(src)) !== null) {
115
- count++;
116
- // Guard against zero-length matches to avoid infinite loop in pathological cases.
117
- if (m[0].length === 0) re.lastIndex++;
118
- }
119
- if (count !== 1) {
120
- throw new Error(
121
- `signature normalization '${norm.name}' did not match exactly once (matched ${count} times)`
122
- );
123
- }
124
- // Now apply the actual replacement (preserve the original flags / backref semantics).
125
- const reNoG = new RegExp(norm.pattern.source, norm.pattern.flags);
126
- src = src.replace(reNoG, norm.replacement);
127
- console.log(` [signature] ${norm.name}: matched ${count}x`);
128
- }
129
- return src;
130
- }
131
-
132
- function addOverrideAnnoAndKeyword(src) {
133
- const lines = src.split(/\r?\n/);
134
- const out = [];
135
- let i = 0;
136
- while (i < lines.length) {
137
- const line = lines[i];
138
- const mAnno = line.match(REACT_METHOD_LINE);
139
- if (mAnno && i + 1 < lines.length) {
140
- const nextLine = lines[i + 1];
141
- const mFun = nextLine.match(FUN_LINE);
142
- if (mFun) {
143
- const name = mFun[2];
144
- if (NON_SPEC_REACT_METHODS.has(name)) {
145
- out.push(line);
146
- out.push(nextLine);
147
- i += 2;
148
- continue;
149
- }
150
- const indent = mAnno[1];
151
- out.push(line);
152
- out.push(`${indent}@Override`);
153
- out.push(`${indent}override fun ${name}${mFun[3]}`);
154
- i += 2;
155
- continue;
156
- }
157
- }
158
- out.push(line);
159
- i += 1;
160
- }
161
- return out.join("\n");
162
- }
163
-
164
- function main() {
165
- let src = fs.readFileSync(SRC_PATH, { encoding: "utf-8" });
166
- // Normalize CRLF -> LF for consistent regex matching. We write LF-only
167
- // back to keep diffs clean (the rest of the file uses LF exclusively
168
- // when checked out via git; the actual byte stream from the edit tool
169
- // happens to also be LF).
170
- src = src.replace(/\r\n/g, "\n");
171
- src = applySignatureNormalizations(src);
172
- src = addOverrideAnnoAndKeyword(src);
173
- fs.writeFileSync(SRC_PATH, src, { encoding: "utf-8" });
174
-
175
- const overrideCount = (src.match(/^ @Override$/mg) || []).length;
176
- const reactMethodCount = (src.match(/^ @ReactMethod/gm) || []).length;
177
- console.log(`Total @ReactMethod blocks: ${reactMethodCount}`);
178
- console.log(`Added @Override annotations: ${overrideCount}`);
179
- console.log(
180
- `Expected: ~${reactMethodCount - NON_SPEC_REACT_METHODS.size} @Override on spec overrides`
181
- );
182
- }
183
-
184
- main();
@@ -1,150 +0,0 @@
1
- #!/usr/bin/env python3
2
- """
3
- V16.0.6 patch release (D-032 / B-010 proper fix):
4
- MpvBridgeModule.kt must extend NativeMpvPlayerSpec. Every @ReactMethod-
5
- annotated function is an override of the spec's abstract method, so we add
6
- `@Override` (Kotlin annotation) on its own line and the `override` keyword
7
- on the `fun` line.
8
-
9
- We also normalize a handful of signature mismatches:
10
- - dumpObservedProperties(): Int → Double (spec returns `double`)
11
- - openPlayer(..., title: String?, ...): Promise
12
- → title: String (spec is non-null)
13
- - enterPip(chapterTitle: String? = null, progressPct: String? = null)
14
- → enterPip(chapterTitle: String, progressPct: String)
15
- (spec is non-null, no defaults; defaults are dropped — the only
16
- internal callers were JS via @ReactMethod)
17
-
18
- Methods NOT in the spec (addListener / removeListeners / startNotification
19
- / updateNotification / stopNotification / initialize lifecycle / the
20
- IMpvConfigProvider & IMpvNativePtrProvider & IPipModeChangeEmitter
21
- implementations) are left untouched so they keep their RN-bridge / private
22
- implementor semantics.
23
-
24
- The toggleMute() stub is added in a separate pass — the spec declares
25
- `abstract void toggleMute();` but MpvBridgeModule.kt 1.5.5 doesn't have
26
- the Kotlin override, so extending NativeMpvPlayerSpec would otherwise
27
- fail to compile with the dreaded
28
- "Class 'MpvBridgeModule' is not abstract and does not override abstract
29
- member 'public abstract void toggleMute()'".
30
- """
31
- import io
32
- import re
33
- import sys
34
-
35
- SRC_PATH = (
36
- "X:/Development/SIMBA/react-native-media-player/android/src/main/java/"
37
- "com/simba/player/mpv/MpvBridgeModule.kt"
38
- )
39
-
40
- # Methods on MpvBridgeModule that have @ReactMethod but are NOT in the
41
- # NativeMpvPlayerSpec (we shouldn't add `override` to them — adding
42
- # `override` would be a Kotlin compiler error since the spec doesn't
43
- # declare them as abstract overrides, and they aren't overrides of
44
- # ReactContextBaseJavaModule either; they're just additional @ReactMethod
45
- # surfaces RN will register).
46
- NON_SPEC_REACT_METHODS = {
47
- "addListener", # RN NativeEventEmitter requirement (line ~1179)
48
- "removeListeners", # RN NativeEventEmitter requirement (line ~1185)
49
- "startNotification", # lib-private notification flow (line ~1508)
50
- "updateNotification",# lib-private notification flow (line ~1541)
51
- "stopNotification", # lib-private notification flow (line ~1570)
52
- }
53
-
54
- # Methods whose signatures must be normalized to match the spec.
55
- # Format: method_name -> (new_return_annotation_or_None, regex_pattern, replacement)
56
- SIGNATURE_NORMALIZATIONS = [
57
- # 1. dumpObservedProperties(): Int -> Double (spec returns double)
58
- (
59
- "dumpObservedProperties",
60
- r"( @ReactMethod\(isBlockingSynchronousMethod = true\)\n)"
61
- r"( fun dumpObservedProperties)\(\): Int \{",
62
- r"\1\2(): Double {",
63
- ),
64
- # 2. openPlayer title: String? -> String
65
- (
66
- "openPlayer",
67
- r"( fun openPlayer\(\n uri: String,\n)"
68
- r" title: String\?,\n",
69
- r"\1 title: String,\n",
70
- ),
71
- # 2b. openPlayer body — title?.takeIf { ... } -> title.takeIf { ... }
72
- (
73
- "openPlayer-body",
74
- r" val resolvedTitle = title\?\.takeIf \{ it\.isNotBlank\(\) \} \?: uri",
75
- " val resolvedTitle = title.takeIf { it.isNotBlank() } ?: uri",
76
- ),
77
- # 3. enterPip: drop nullable types + defaults
78
- (
79
- "enterPip",
80
- r" fun enterPip\(chapterTitle: String\? = null, progressPct: String\? = null\) \{",
81
- " fun enterPip(chapterTitle: String, progressPct: String) {",
82
- ),
83
- ]
84
-
85
-
86
- def main() -> int:
87
- with open(SRC_PATH, "r", encoding="utf-8") as f:
88
- src = f.read()
89
-
90
- # Step 1 — apply signature normalizations BEFORE adding @Override so the
91
- # capture groups line up cleanly with the existing lines.
92
- for name, pattern, replacement in SIGNATURE_NORMALIZATIONS:
93
- new_src, n = re.subn(pattern, replacement, src, count=1)
94
- if n != 1:
95
- print(f"ERROR: signature normalization '{name}' did not match exactly once (matched {n} times)", file=sys.stderr)
96
- return 2
97
- print(f" [signature] {name}: matched {n}x")
98
- src = new_src
99
-
100
- # Step 2 — convert each @ReactMethod fun <name>... block to add
101
- # `@Override` annotation and `override` keyword. We do this line by
102
- # line so the regex pattern is unambiguous.
103
- lines = io.StringIO(src).readlines()
104
- out: list[str] = []
105
- i = 0
106
- while i < len(lines):
107
- line = lines[i]
108
- # Match `@ReactMethod` (with optional params) on its own indented line,
109
- # followed by an indented `fun <ident>(...) ... {` line.
110
- m_anno = re.match(r"^( )(@ReactMethod(?:\([^)]*\))?)\s*$", line)
111
- if m_anno and i + 1 < len(lines):
112
- next_line = lines[i + 1]
113
- m_fun = re.match(
114
- r"^( )fun (?P<name>[A-Za-z_][A-Za-z0-9_]*)(?P<rest>\(.*)$",
115
- next_line,
116
- )
117
- if m_fun:
118
- name = m_fun.group("name")
119
- if name in NON_SPEC_REACT_METHODS:
120
- out.append(line)
121
- out.append(next_line)
122
- i += 2
123
- continue
124
- indent = m_anno.group(1)
125
- # Add @Override on its own line. Use the same indent.
126
- out.append(line) # @ReactMethod(...)
127
- out.append(f"{indent}@Override\n") # @Override
128
- out.append(f"{indent}override fun {name}{m_fun.group('rest')}\n") # override fun ...
129
- i += 2
130
- continue
131
- out.append(line)
132
- i += 1
133
-
134
- new_src = "".join(out)
135
-
136
- # Write back
137
- with open(SRC_PATH, "w", encoding="utf-8") as f:
138
- f.write(new_src)
139
-
140
- # Quick sanity: count the @Override we added
141
- override_count = new_src.count(" @Override\n")
142
- react_method_count = len(re.findall(r"^ @ReactMethod", new_src, flags=re.MULTILINE))
143
- print(f"Total @ReactMethod blocks: {react_method_count}")
144
- print(f"Added @Override annotations: {override_count}")
145
- print(f"Expected: ~{react_method_count - len(NON_SPEC_REACT_METHODS)} @Override on spec overrides")
146
- return 0
147
-
148
-
149
- if __name__ == "__main__":
150
- sys.exit(main())