@simba-dev/react-native-media-player 1.11.0 → 1.13.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.
@@ -10,47 +10,80 @@ import android.content.Intent
10
10
  import android.graphics.Bitmap
11
11
  import android.graphics.BitmapFactory
12
12
  import android.os.Build
13
+ import android.os.Handler
13
14
  import android.os.IBinder
15
+ import android.os.Looper
16
+ import android.support.v4.media.MediaMetadataCompat
14
17
  import android.support.v4.media.session.MediaSessionCompat
15
18
  import android.support.v4.media.session.PlaybackStateCompat
16
19
  import android.util.Log
17
20
  import androidx.core.app.NotificationCompat
21
+ import com.simba.player.mpv.MPVLib
18
22
  import java.io.File
19
23
  import java.net.URL
20
24
 
21
25
  /**
22
- * V12 Wave 4 Phase 16: foreground service that hosts the persistent
23
- * media-style notification for `PlayerActivity`.
26
+ * V20 Phase B: the foreground service that owns playback.
24
27
  *
25
- * Why a service?
26
- * - Android can kill backgrounded activities, but a foreground service
27
- * has UI-importance guarantees that keep the audio/video process
28
- * alive while playback is in progress.
29
- * - The media-style notification is the user-facing surface for
30
- * playback controls (play/pause, next, prev) outside the
31
- * PiP / lock-screen / Bluetooth paths.
28
+ * ## What changed, and why
32
29
  *
33
- * Why module-local?
34
- * - The V11 `MediaNotificationService` lives in the consumer app for
35
- * the inline-mount path. V12's dedicated `PlayerActivity` needs its
36
- * own notification host, and the module is the right home for it
37
- * (so any consumer app that installs `@simba/react-native-media-player`
38
- * gets the notification wiring for free).
30
+ * Before V20 this service was a notification *host*: `PlayerActivity`
31
+ * created the [MediaSessionCompat], and the Activity passed its token in
32
+ * the start intent so the notification's `MediaStyle` could point at it.
33
+ * The class docblock stated the design intent explicitly — *"the service
34
+ * does NOT own the `MediaSessionCompat` … This keeps the source of truth
35
+ * for playback state in the activity"*.
39
36
  *
40
- * Session token: the service does NOT own the `MediaSessionCompat` —
41
- * `PlayerActivity` does (Phase 15). The activity passes the session
42
- * token in the start intent's `EXTRA_SESSION_TOKEN` extra so the
43
- * `MediaStyle` notification can wire its controls to the same
44
- * `MediaSessionCompat.Callback` the activity registered. This keeps
45
- * the source of truth for playback state in the activity (where the
46
- * mpv pointer lives) and lets the service focus on the notification.
37
+ * That is the arrangement Media3's guidance puts the other way round:
47
38
  *
48
- * Permissions: the consumer app must declare
49
- * <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
50
- * <uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK" />
51
- * in its own manifest (the V11 app already declares the first; the
52
- * second is API 34+). The library manifest declares the service
53
- * component itself.
39
+ * > "To enable background playback, you should contain the Player and
40
+ * > MediaSession inside a separate Service."
41
+ * > "onCreate() … It's the best place to build Player and MediaSession.
42
+ * > onDestroy() … All resources including player and session need to be
43
+ * > released."
44
+ * > — https://developer.android.com/media/media3/session/background-playback
45
+ *
46
+ * The practical cost of getting it backwards was that the session died
47
+ * with the Activity, so "hide the player" and "shut the player down"
48
+ * were the same verb, and a mini player could not exist. The session now
49
+ * lives here, is released here, and outlives any UI.
50
+ *
51
+ * (The docblock's other claim — that the mpv pointer lives "in the
52
+ * activity" — was wrong even before V20. It lives in C++, process-global
53
+ * as `g_mpv`, and is mirrored by [PlaybackHost].)
54
+ *
55
+ * ## The engine is process-global, so no IPC is needed
56
+ *
57
+ * Media3 separates the session server from its UI with `MediaController`
58
+ * because they may be in different processes. Here they are always in
59
+ * one process, and the engine is a C++ global
60
+ * (`native_state.h:13`) reached through the [MPVLib] singleton. So this
61
+ * service issues transport commands directly via [PlaybackHost.handle()]
62
+ * rather than going through a controller indirection, and same-process
63
+ * callers reach it through [instance]. Media3's own session demo has the
64
+ * same shape: `MainActivity` + `PlayerActivity` + `PlaybackService`, with
65
+ * the service owning the player and session.
66
+ *
67
+ * ## Why the notification has no hand-added buttons
68
+ *
69
+ * V20 Phase B replaced these handlers, which did nothing:
70
+ *
71
+ * ```
72
+ * ACTION_SKIP_NEXT -> Log.d(TAG, "... (MediaSession is the source of truth)")
73
+ * ACTION_SKIP_PREV -> Log.d(TAG, "... (MediaSession is the source of truth)")
74
+ * ```
75
+ *
76
+ * with real commands - but *also* kept our own action buttons on top of a
77
+ * session-backed MediaStyle. Device verification showed both sets rendering at
78
+ * once: two play-looking buttons and no way to tell which one was live. That
79
+ * is the "control that may or may not be the real one" ambiguity the whole
80
+ * change set out to remove, reintroduced by the fix.
81
+ *
82
+ * The buttons are gone. A MediaStyle carrying a session token renders the
83
+ * transport controls from the session advertised actions and routes taps to
84
+ * the session callback, which issues the real command - so the session alone
85
+ * is the single path. ACTION_SEEK_TO is advertised, which is what makes the
86
+ * progress bar seekable rather than decorative.
54
87
  */
55
88
  class MediaPlaybackService : Service() {
56
89
 
@@ -59,16 +92,31 @@ class MediaPlaybackService : Service() {
59
92
  const val CHANNEL_ID = "simba_player_media_playback"
60
93
  const val NOTIFICATION_ID = 1101
61
94
 
95
+ /**
96
+ * How often the service refreshes its own position cache, the
97
+ * session state and the notification. Matches the 1Hz the
98
+ * Activity-side ticker used to run at; the notification is the
99
+ * coarsest consumer of the three, so going finer would spend
100
+ * wake-ups on something no user can see move.
101
+ */
102
+ private const val TICK_INTERVAL_MS = 1000L
103
+
62
104
  // Intent actions
63
105
  const val ACTION_START = "com.simba.player.MEDIA_PLAYBACK_START"
64
106
  const val ACTION_UPDATE = "com.simba.player.MEDIA_PLAYBACK_UPDATE"
65
107
  const val ACTION_STOP = "com.simba.player.MEDIA_PLAYBACK_STOP"
66
- const val ACTION_PLAY_PAUSE = "com.simba.player.MEDIA_PLAYBACK_PLAY_PAUSE"
67
- const val ACTION_SKIP_NEXT = "com.simba.player.MEDIA_PLAYBACK_SKIP_NEXT"
68
- const val ACTION_SKIP_PREV = "com.simba.player.MEDIA_PLAYBACK_SKIP_PREV"
108
+
109
+ // V20 Phase B originally added ACTION_PLAY_PAUSE / ACTION_SKIP_NEXT /
110
+ // ACTION_SKIP_PREV / ACTION_SEEK_TO so the notification's own
111
+ // action buttons had somewhere to land. Those buttons are gone -
112
+ // see buildNotification(). A MediaStyle carrying a session token
113
+ // renders the transport controls from the session's advertised
114
+ // actions and routes taps to the session callback, so these
115
+ // handlers were reachable from nowhere and were deleted rather
116
+ // than left in place as plausible-looking dead code.
69
117
 
70
118
  // Intent extras (kept in sync with PlayerActivity's
71
- // [buildStartIntent] helper).
119
+ // [buildMediaPlaybackServiceIntent] helper).
72
120
  const val EXTRA_TITLE = "title"
73
121
  const val EXTRA_ARTIST = "artist"
74
122
  const val EXTRA_ALBUM = "album"
@@ -76,6 +124,12 @@ class MediaPlaybackService : Service() {
76
124
  const val EXTRA_POSITION_MS = "positionMs"
77
125
  const val EXTRA_DURATION_MS = "durationMs"
78
126
  const val EXTRA_IS_PLAYING = "isPlaying"
127
+ /**
128
+ * Retained for wire compatibility with an already-installed
129
+ * 1.x consumer that still puts a token in the start intent. The
130
+ * service ignores it — it owns the session now and publishes its
131
+ * own token to the notification.
132
+ */
79
133
  const val EXTRA_SESSION_TOKEN = "sessionToken"
80
134
 
81
135
  // Notification action indices (compact view ordering)
@@ -86,8 +140,44 @@ class MediaPlaybackService : Service() {
86
140
  @Volatile
87
141
  private var isRunning = false
88
142
 
143
+ /**
144
+ * The running instance, for same-process callers.
145
+ *
146
+ * This is a convenience handle, not an ownership mechanism: the
147
+ * session and the notification are created and released by the
148
+ * Service's own lifecycle regardless of who holds a reference.
149
+ * It mirrors the existing `currentActivityIsPlayer` pattern used
150
+ * elsewhere in this library.
151
+ */
152
+ @Volatile
153
+ private var instance: MediaPlaybackService? = null
154
+
89
155
  fun isRunning(): Boolean = isRunning
90
156
 
157
+ /**
158
+ * Publish a playback state to the session, if the service is up.
159
+ *
160
+ * Callers are UI. If the service is not running there is no
161
+ * session to publish to and no playback to describe, so this is a
162
+ * deliberate no-op rather than a queued write — a UI must never
163
+ * be the thing that resurrects a torn-down session.
164
+ */
165
+ fun publishState(playing: Boolean, state: Int = PlaybackStateCompat.STATE_PLAYING) {
166
+ instance?.publishPlaybackState(playing, state)
167
+ }
168
+
169
+ /** Publish metadata to the session and refresh the notification. */
170
+ fun publishMetadata(
171
+ title: String,
172
+ artist: String,
173
+ album: String,
174
+ artworkPath: String,
175
+ mediaUri: String,
176
+ displaySubtitle: String,
177
+ ) {
178
+ instance?.applyMetadata(title, artist, album, artworkPath, mediaUri, displaySubtitle)
179
+ }
180
+
91
181
  /**
92
182
  * Build a [PendingIntent] for a notification action targeting
93
183
  * this service. FLAG_IMMUTABLE is mandatory on API 31+ for
@@ -106,9 +196,9 @@ class MediaPlaybackService : Service() {
106
196
  }
107
197
 
108
198
  /**
109
- * Build a PendingIntent that opens `PlayerActivity`. Used
199
+ * Build a [PendingIntent] that opens `PlayerActivity`. Used
110
200
  * when the user taps the notification body — returns them
111
- * to the player if it's still alive, or launches a fresh
201
+ * to the player if its task is still alive, or launches a fresh
112
202
  * instance otherwise.
113
203
  */
114
204
  private fun buildContentIntent(context: Context): PendingIntent {
@@ -129,6 +219,12 @@ class MediaPlaybackService : Service() {
129
219
 
130
220
  private lateinit var notificationManager: NotificationManager
131
221
 
222
+ /**
223
+ * V20 Phase B: the session is created here and released in this
224
+ * service's `onDestroy`, not in an Activity's.
225
+ */
226
+ private var mediaSession: MediaSessionCompat? = null
227
+
132
228
  // Cached metadata for the latest notification rebuild.
133
229
  private var currentTitle: String = "Simba Player"
134
230
  private var currentArtist: String = ""
@@ -137,59 +233,311 @@ class MediaPlaybackService : Service() {
137
233
  private var currentPosition: Long = 0L
138
234
  private var currentDuration: Long = 0L
139
235
  private var isCurrentlyPlaying: Boolean = true
140
- private var sessionToken: MediaSessionCompat.Token? = null
236
+
237
+ // ── Position ticker (V20 Phase C) ──────────────────────────────────────
238
+
239
+ /**
240
+ * This service owns its own 1Hz position ticker.
241
+ *
242
+ * It used to be driven by `PlayerActivity`'s
243
+ * `progressUpdateRunnable`, which only ran between that Activity's
244
+ * `onResume` and `onPause`. Once the window went away the tick stopped
245
+ * and `currentPosition` froze: the session's own state kept
246
+ * extrapolating via `speed = 1.0f`, so the system's lock-screen
247
+ * widget looked alive, while the notification's progress bar and this
248
+ * cache went stale. Two clocks disagreeing is worse than one frozen
249
+ * clock, because it reads as a bug in whichever one you are watching.
250
+ *
251
+ * It has to live here. With V20 Phase C, audio no longer opens an
252
+ * Activity at all, so there is frequently nothing left to drive a
253
+ * ticker that lived on an Activity — the notification would simply
254
+ * never move.
255
+ *
256
+ * Reads the engine directly each tick rather than trusting
257
+ * [isCurrentlyPlaying], so a track that ends underneath us (EOF) is
258
+ * noticed instead of being reported as playing forever.
259
+ */
260
+ private val tickerHandler = Handler(Looper.getMainLooper())
261
+ private var tickerRunning = false
262
+
263
+ private val positionTicker = object : Runnable {
264
+ override fun run() {
265
+ if (!tickerRunning) return
266
+ if (ptr() == 0L) {
267
+ // Engine torn down under us. Stop instead of spinning at
268
+ // 1Hz against a dead handle for as long as the service lives.
269
+ Log.w(TAG, "position ticker stopping: no engine handle")
270
+ tickerRunning = false
271
+ return
272
+ }
273
+ val idle = engineFlag("idle-active")
274
+ if (idle) {
275
+ // Nothing is loaded or the file reached its end. Publishing
276
+ // PLAYING here is how "the notification says it is playing
277
+ // and nothing is audible" happens.
278
+ Log.i(TAG, "position ticker: engine idle, publishing stopped state")
279
+ tickerRunning = false
280
+ publishPlaybackState(playing = false, state = PlaybackStateCompat.STATE_STOPPED)
281
+ notificationManager.notify(NOTIFICATION_ID, buildNotification())
282
+ return
283
+ }
284
+ val paused = engineFlag("pause")
285
+ isCurrentlyPlaying = !paused
286
+ publishPlaybackState(playing = !paused)
287
+ notificationManager.notify(NOTIFICATION_ID, buildNotification())
288
+ tickerHandler.postDelayed(this, TICK_INTERVAL_MS)
289
+ }
290
+ }
291
+
292
+ private fun startTicker() {
293
+ if (tickerRunning) return
294
+ tickerRunning = true
295
+ tickerHandler.postDelayed(positionTicker, TICK_INTERVAL_MS)
296
+ Log.i(TAG, "position ticker started (interval=${TICK_INTERVAL_MS}ms)")
297
+ }
298
+
299
+ private fun stopTicker(reason: String) {
300
+ if (!tickerRunning) return
301
+ tickerRunning = false
302
+ tickerHandler.removeCallbacks(positionTicker)
303
+ Log.i(TAG, "position ticker stopped ($reason)")
304
+ }
141
305
 
142
306
  // ── Lifecycle ──────────────────────────────────────────────────────────
143
307
 
144
308
  override fun onCreate() {
145
309
  super.onCreate()
310
+ instance = this
146
311
  notificationManager = getSystemService(NotificationManager::class.java)
147
312
  createNotificationChannel()
148
- Log.i(TAG, "MediaPlaybackService created")
313
+ createMediaSession()
314
+ Log.i(TAG, "MediaPlaybackService created (session owned by service)")
149
315
  }
150
316
 
151
317
  override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
152
318
  when (intent?.action) {
153
319
  ACTION_UPDATE -> handleUpdate(intent)
154
- ACTION_STOP -> {
155
- stopForeground(STOP_FOREGROUND_REMOVE)
156
- stopSelf()
157
- }
158
- // Phase 16: notification action handlers. The actual
159
- // play/pause / skip / stop calls go through the
160
- // MediaSessionCompat (Phase 15) — PlayerActivity's
161
- // callback translates them into MPVLib calls. These
162
- // handlers just optimistically update the cached state
163
- // so the notification UI feels responsive even before
164
- // MPVLib confirms.
165
- ACTION_PLAY_PAUSE -> handlePlayPause()
166
- ACTION_SKIP_NEXT -> Log.d(TAG, "ACTION_SKIP_NEXT (MediaSession is the source of truth)")
167
- ACTION_SKIP_PREV -> Log.d(TAG, "ACTION_SKIP_PREV (MediaSession is the source of truth)")
320
+ ACTION_STOP -> handleStop()
168
321
  else -> handleStart(intent)
169
322
  }
170
323
  return START_REDELIVER_INTENT
171
324
  }
172
325
 
173
- private fun handlePlayPause() {
174
- // Toggle local state for instant UI feedback; the
175
- // MediaSessionCompat callback in PlayerActivity (Phase 15)
176
- // will issue the actual MPVLib play/pause and call
177
- // updateMediaSessionState, which feeds back into a
178
- // ACTION_UPDATE intent and syncs us up.
179
- isCurrentlyPlaying = !isCurrentlyPlaying
180
- notificationManager.notify(NOTIFICATION_ID, buildNotification())
181
- Log.d(TAG, "ACTION_PLAY_PAUSE: optimistically toggled to playing=$isCurrentlyPlaying")
182
- }
183
-
184
326
  override fun onBind(intent: Intent?): IBinder? = null
185
327
 
186
328
  override fun onDestroy() {
329
+ // Media3 puts player + session release in the *service's*
330
+ // onDestroy. Doing it in an Activity's is what tied the session's
331
+ // lifetime to a window.
332
+ stopTicker("service destroyed")
333
+ releaseMediaSession()
187
334
  isRunning = false
335
+ instance = null
188
336
  notificationManager.cancel(NOTIFICATION_ID)
189
337
  Log.i(TAG, "MediaPlaybackService destroyed")
190
338
  super.onDestroy()
191
339
  }
192
340
 
341
+ // ── Session ownership ──────────────────────────────────────────────────
342
+
343
+ /**
344
+ * The full transport set, issued against the process-global engine.
345
+ *
346
+ * Every handler reads the handle at the moment of use via
347
+ * [PlaybackHost] rather than caching it — a cached copy is what let
348
+ * an Activity's controls go silently dead after a destroy/re-create.
349
+ */
350
+ private fun createMediaSession() {
351
+ val callback = object : MediaSessionCompat.Callback() {
352
+ override fun onPlay() = command("onPlay") {
353
+ MPVLib.nativePlay(ptr())
354
+ publishPlaybackState(playing = true)
355
+ startTicker()
356
+ }
357
+
358
+ override fun onPause() = command("onPause") {
359
+ MPVLib.nativePause(ptr())
360
+ publishPlaybackState(playing = false)
361
+ stopTicker("paused")
362
+ }
363
+
364
+ override fun onStop() = command("onStop") {
365
+ MPVLib.nativeStop(ptr())
366
+ publishPlaybackState(playing = false, state = PlaybackStateCompat.STATE_STOPPED)
367
+ stopTicker("stopped")
368
+ }
369
+
370
+ override fun onSkipToNext() = command("onSkipToNext") {
371
+ MPVLib.nativePlaylistNext(ptr())
372
+ publishPlaybackState(playing = true)
373
+ startTicker()
374
+ }
375
+
376
+ override fun onSkipToPrevious() = command("onSkipToPrevious") {
377
+ MPVLib.nativePlaylistPrev(ptr())
378
+ publishPlaybackState(playing = true)
379
+ startTicker()
380
+ }
381
+
382
+ override fun onSeekTo(pos: Long) = command("onSeekTo($pos)") {
383
+ if (pos >= 0L) MPVLib.nativeSeek(ptr(), pos.toDouble() / 1000.0)
384
+ }
385
+ }
386
+
387
+ val session = MediaSessionCompat(this, TAG).apply {
388
+ setFlags(
389
+ MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS or
390
+ MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS,
391
+ )
392
+ setCallback(callback)
393
+ // Tapping the lock-screen widget should surface the player.
394
+ val activityIntent = Intent().apply {
395
+ setClassName(this@MediaPlaybackService, "com.simba.player.PlayerActivity")
396
+ flags = Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP
397
+ }
398
+ setSessionActivity(
399
+ PendingIntent.getActivity(
400
+ this@MediaPlaybackService,
401
+ 0,
402
+ activityIntent,
403
+ PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
404
+ ),
405
+ )
406
+ isActive = true
407
+ }
408
+ mediaSession = session
409
+ publishPlaybackState(playing = true)
410
+ Log.i(TAG, "MediaSession created and owned by the service")
411
+ }
412
+
413
+ private fun releaseMediaSession() {
414
+ val session = mediaSession ?: return
415
+ try {
416
+ session.isActive = false
417
+ session.release()
418
+ Log.i(TAG, "MediaSession released")
419
+ } catch (e: Exception) {
420
+ Log.w(TAG, "releaseMediaSession: ${e.message}", e)
421
+ } finally {
422
+ mediaSession = null
423
+ }
424
+ }
425
+
426
+ /**
427
+ * Run [block] against the engine, or explain why it could not run.
428
+ *
429
+ * A transport command that silently does nothing is the exact defect
430
+ * this class used to contain, so "no engine" is logged rather than
431
+ * swallowed.
432
+ */
433
+ private inline fun command(label: String, block: () -> Unit) {
434
+ if (ptr() == 0L) {
435
+ Log.w(TAG, "MediaSession.$label ignored: no engine handle")
436
+ return
437
+ }
438
+ try {
439
+ block()
440
+ } catch (e: Exception) {
441
+ Log.w(TAG, "MediaSession.$label threw ${e.message}", e)
442
+ }
443
+ }
444
+
445
+ private fun ptr(): Long = PlaybackHost.handle()
446
+
447
+ private fun enginePropertyMs(name: String): Long {
448
+ val handle = ptr()
449
+ if (handle == 0L) return 0L
450
+ return try {
451
+ MPVLib.nativeGetProperty(handle, name).trim().toDoubleOrNull()?.times(1000.0)?.toLong() ?: 0L
452
+ } catch (_: Exception) {
453
+ 0L
454
+ }
455
+ }
456
+
457
+ private fun engineProperty(name: String): String {
458
+ val handle = ptr()
459
+ if (handle == 0L) return ""
460
+ return try {
461
+ MPVLib.nativeGetProperty(handle, name).trim()
462
+ } catch (_: Exception) {
463
+ ""
464
+ }
465
+ }
466
+
467
+ /**
468
+ * mpv renders boolean properties as the strings `"yes"` / `"no"`.
469
+ *
470
+ * Anything else — empty, `"null"`, a parse error — is reported as
471
+ * `false`, because "I could not read this" must not be mistaken for
472
+ * "this is true". A ticker's whole job is to be trustworthy.
473
+ */
474
+ private fun engineFlag(name: String): Boolean =
475
+ engineProperty(name).equals("yes", ignoreCase = true)
476
+
477
+ /** Push the current transport state into the session. */
478
+ private fun publishPlaybackState(
479
+ playing: Boolean,
480
+ state: Int = if (playing) PlaybackStateCompat.STATE_PLAYING else PlaybackStateCompat.STATE_PAUSED,
481
+ ) {
482
+ val session = mediaSession ?: return
483
+ val positionMs = enginePropertyMs("time-pos")
484
+ val builder = PlaybackStateCompat.Builder()
485
+ .setActions(
486
+ PlaybackStateCompat.ACTION_PLAY or
487
+ PlaybackStateCompat.ACTION_PAUSE or
488
+ PlaybackStateCompat.ACTION_PLAY_PAUSE or
489
+ PlaybackStateCompat.ACTION_STOP or
490
+ PlaybackStateCompat.ACTION_SKIP_TO_NEXT or
491
+ PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS or
492
+ // Advertised, so the notification's progress bar is
493
+ // genuinely seekable rather than a decoration.
494
+ PlaybackStateCompat.ACTION_SEEK_TO,
495
+ )
496
+ .setState(state, positionMs, 1.0f)
497
+ session.setPlaybackState(builder.build())
498
+
499
+ // Keep the notification's own cache in step so its progress bar
500
+ // and play/pause glyph reflect reality rather than optimism.
501
+ currentPosition = positionMs
502
+ currentDuration = enginePropertyMs("duration")
503
+ isCurrentlyPlaying = playing
504
+ }
505
+
506
+ private fun applyMetadata(
507
+ title: String,
508
+ artist: String,
509
+ album: String,
510
+ artworkPath: String,
511
+ mediaUri: String,
512
+ displaySubtitle: String,
513
+ ) {
514
+ if (title.isNotBlank()) currentTitle = title
515
+ currentArtist = artist
516
+ currentAlbum = album
517
+ currentArtworkPath = artworkPath
518
+
519
+ val session = mediaSession ?: return
520
+ val durationMs = enginePropertyMs("duration")
521
+ val builder = MediaMetadataCompat.Builder()
522
+ .putString(MediaMetadataCompat.METADATA_KEY_TITLE, currentTitle)
523
+ .putString(MediaMetadataCompat.METADATA_KEY_DISPLAY_TITLE, currentTitle)
524
+ if (currentArtist.isNotBlank()) {
525
+ builder.putString(MediaMetadataCompat.METADATA_KEY_ARTIST, currentArtist)
526
+ }
527
+ if (currentAlbum.isNotBlank()) {
528
+ builder.putString(MediaMetadataCompat.METADATA_KEY_ALBUM, currentAlbum)
529
+ }
530
+ if (displaySubtitle.isNotBlank()) {
531
+ builder.putString(MediaMetadataCompat.METADATA_KEY_DISPLAY_SUBTITLE, displaySubtitle)
532
+ }
533
+ if (mediaUri.isNotBlank()) {
534
+ builder.putString(MediaMetadataCompat.METADATA_KEY_MEDIA_URI, mediaUri)
535
+ }
536
+ if (durationMs > 0L) builder.putLong(MediaMetadataCompat.METADATA_KEY_DURATION, durationMs)
537
+ session.setMetadata(builder.build())
538
+ notificationManager.notify(NOTIFICATION_ID, buildNotification())
539
+ }
540
+
193
541
  // ── Action Handlers ────────────────────────────────────────────────────
194
542
 
195
543
  private fun handleStart(intent: Intent?) {
@@ -201,14 +549,13 @@ class MediaPlaybackService : Service() {
201
549
  currentPosition = extras?.getLong(EXTRA_POSITION_MS, 0L) ?: 0L
202
550
  currentDuration = extras?.getLong(EXTRA_DURATION_MS, 0L) ?: 0L
203
551
  isCurrentlyPlaying = extras?.getBoolean(EXTRA_IS_PLAYING, true) ?: true
204
- sessionToken = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
205
- extras?.getParcelable(EXTRA_SESSION_TOKEN) as? MediaSessionCompat.Token
206
- } else {
207
- null
208
- }
209
552
  isRunning = true
210
- val notification = buildNotification()
211
- startForeground(NOTIFICATION_ID, notification)
553
+ applyMetadata(currentTitle, currentArtist, currentAlbum, currentArtworkPath, "", "")
554
+ startForeground(NOTIFICATION_ID, buildNotification())
555
+ // Phase C: the engine has already been handed the file by the
556
+ // caller before this intent was built, so the ticker starts
557
+ // against a live engine rather than an empty one.
558
+ if (isCurrentlyPlaying) startTicker() else stopTicker("start without autoplay")
212
559
  Log.i(
213
560
  TAG,
214
561
  "Media playback started: title='$currentTitle' artist='$currentArtist' playing=$isCurrentlyPlaying",
@@ -228,6 +575,16 @@ class MediaPlaybackService : Service() {
228
575
  Log.d(TAG, "Media playback updated: position=$currentPosition playing=$isCurrentlyPlaying")
229
576
  }
230
577
 
578
+ private fun handleStop() {
579
+ stopTicker("stop command")
580
+ command("notification-stop") {
581
+ if (ptr() != 0L) MPVLib.nativeStop(ptr())
582
+ }
583
+ publishPlaybackState(playing = false, state = PlaybackStateCompat.STATE_STOPPED)
584
+ stopForeground(STOP_FOREGROUND_REMOVE)
585
+ stopSelf()
586
+ }
587
+
231
588
  // ── Notification Channel (Android 8+) ──────────────────────────────────
232
589
 
233
590
  private fun createNotificationChannel() {
@@ -251,18 +608,16 @@ class MediaPlaybackService : Service() {
251
608
  // ── Notification Building ──────────────────────────────────────────────
252
609
 
253
610
  private fun buildNotification(): Notification {
254
- val playbackAction = if (isCurrentlyPlaying) {
255
- android.R.drawable.ic_media_pause
256
- } else {
257
- android.R.drawable.ic_media_play
258
- }
259
- val playbackContent = if (isCurrentlyPlaying) "Pause" else "Play"
260
-
261
- val subtitle: String? = when {
611
+ // Never null. `setContentText(null)` renders the literal string
612
+ // "null" in the MediaStyle subtitle when artist and album are both
613
+ // blank - which is every untagged file. An untagged item should
614
+ // show nothing, not the word "null".
615
+ val subtitle = when {
262
616
  currentArtist.isNotBlank() && currentAlbum.isNotBlank() ->
263
617
  "$currentArtist • $currentAlbum"
264
618
  currentArtist.isNotBlank() -> currentArtist
265
- else -> null
619
+ currentAlbum.isNotBlank() -> currentAlbum
620
+ else -> ""
266
621
  }
267
622
 
268
623
  val artwork: Bitmap? = loadArtworkBitmap(currentArtworkPath) ?: BitmapFactory.decodeResource(
@@ -283,42 +638,36 @@ class MediaPlaybackService : Service() {
283
638
  .setSilent(true)
284
639
  .setOnlyAlertOnce(true)
285
640
 
286
- // MediaStyle: wire to the session token PlayerActivity
287
- // passed in via EXTRA_SESSION_TOKEN so the notification's
288
- // playback state matches the activity's MediaSession
289
- // (Phase 15). If the token was lost across an activity
290
- // rebuild, the style still renders (just without the
291
- // session integration).
292
- val token = sessionToken
641
+ // MediaStyle points at *this service's own* session — no token
642
+ // has to be handed in by an Activity any more.
643
+ //
644
+ // No manual actions are added here, deliberately.
645
+ //
646
+ // Once a MediaStyle carries a session token, the system renders
647
+ // the transport controls from `session.playbackState.actions` and
648
+ // routes taps to the session callback. Adding our own on top
649
+ // produced TWO overlapping control sets on device - two
650
+ // play-looking buttons and an ambiguous tap target - which is
651
+ // exactly the "control that may or may not be the real one"
652
+ // ambiguity this class was rewritten to remove.
653
+ //
654
+ // The session advertises PLAY / PAUSE / PLAY_PAUSE / STOP /
655
+ // SKIP_TO_NEXT / SKIP_TO_PREVIOUS / SEEK_TO, so every control we
656
+ // need is already rendered and already wired to a real command.
657
+ // Stop additionally gets the MediaStyle cancel button below.
658
+ val session = mediaSession
293
659
  val mediaStyle = androidx.media.app.NotificationCompat.MediaStyle()
294
660
  .setShowActionsInCompactView(INDEX_PLAY, INDEX_NEXT, INDEX_PREV)
295
661
  .setShowCancelButton(true)
296
662
  .setCancelButtonIntent(buildActionIntent(this, ACTION_STOP))
297
- if (token != null) {
298
- mediaStyle.setMediaSession(token)
663
+ if (session != null) {
664
+ mediaStyle.setMediaSession(session.sessionToken)
299
665
  }
300
666
  builder.setStyle(mediaStyle)
301
667
 
302
- // Action buttons
303
- builder.addAction(
304
- android.R.drawable.ic_media_previous,
305
- "Previous",
306
- buildActionIntent(this, ACTION_SKIP_PREV),
307
- )
308
- builder.addAction(playbackAction, playbackContent, buildActionIntent(this, ACTION_PLAY_PAUSE))
309
- builder.addAction(
310
- android.R.drawable.ic_media_next,
311
- "Next",
312
- buildActionIntent(this, ACTION_SKIP_NEXT),
313
- )
314
- builder.addAction(
315
- android.R.drawable.ic_menu_close_clear_cancel,
316
- "Stop",
317
- buildActionIntent(this, ACTION_STOP),
318
- )
319
-
320
- // Progress bar (seekable on Android 12+ when the session
321
- // exposes SEEK_TO; not used here yet — Phase 20 wires it).
668
+ // Progress bar. Seekable now, because the session advertises
669
+ // ACTION_SEEK_TO - which is what makes the system render this
670
+ // seekable rather than as decoration.
322
671
  if (currentDuration > 0L) {
323
672
  builder.setProgress(
324
673
  currentDuration.toInt(),
@@ -355,31 +704,4 @@ class MediaPlaybackService : Service() {
355
704
  null
356
705
  }
357
706
  }
358
-
359
- // ── State Builders for Session (used when token is set) ────────────────
360
-
361
- /**
362
- * Build a [PlaybackStateCompat] from the cached fields. Called
363
- * when the notification is rebuilt with a session token; the
364
- * session's own [MediaSessionCompat.Callback] in `PlayerActivity`
365
- * (Phase 15) handles the actual play/pause/seek calls.
366
- */
367
- private fun buildPlaybackStateCompat(): PlaybackStateCompat {
368
- val state = if (isCurrentlyPlaying) {
369
- PlaybackStateCompat.STATE_PLAYING
370
- } else {
371
- PlaybackStateCompat.STATE_PAUSED
372
- }
373
- return PlaybackStateCompat.Builder()
374
- .setActions(
375
- PlaybackStateCompat.ACTION_PLAY or
376
- PlaybackStateCompat.ACTION_PAUSE or
377
- PlaybackStateCompat.ACTION_PLAY_PAUSE or
378
- PlaybackStateCompat.ACTION_SKIP_TO_NEXT or
379
- PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS or
380
- PlaybackStateCompat.ACTION_STOP,
381
- )
382
- .setState(state, currentPosition, 1.0f)
383
- .build()
384
- }
385
707
  }