@simba-dev/react-native-media-player 1.10.0 → 1.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.
@@ -11,46 +11,74 @@ import android.graphics.Bitmap
11
11
  import android.graphics.BitmapFactory
12
12
  import android.os.Build
13
13
  import android.os.IBinder
14
+ import android.support.v4.media.MediaMetadataCompat
14
15
  import android.support.v4.media.session.MediaSessionCompat
15
16
  import android.support.v4.media.session.PlaybackStateCompat
16
17
  import android.util.Log
17
18
  import androidx.core.app.NotificationCompat
19
+ import com.simba.player.mpv.MPVLib
18
20
  import java.io.File
19
21
  import java.net.URL
20
22
 
21
23
  /**
22
- * V12 Wave 4 Phase 16: foreground service that hosts the persistent
23
- * media-style notification for `PlayerActivity`.
24
+ * V20 Phase B: the foreground service that owns playback.
24
25
  *
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.
26
+ * ## What changed, and why
32
27
  *
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).
28
+ * Before V20 this service was a notification *host*: `PlayerActivity`
29
+ * created the [MediaSessionCompat], and the Activity passed its token in
30
+ * the start intent so the notification's `MediaStyle` could point at it.
31
+ * The class docblock stated the design intent explicitly — *"the service
32
+ * does NOT own the `MediaSessionCompat` … This keeps the source of truth
33
+ * for playback state in the activity"*.
39
34
  *
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.
35
+ * That is the arrangement Media3's guidance puts the other way round:
47
36
  *
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.
37
+ * > "To enable background playback, you should contain the Player and
38
+ * > MediaSession inside a separate Service."
39
+ * > "onCreate() … It's the best place to build Player and MediaSession.
40
+ * > onDestroy() … All resources including player and session need to be
41
+ * > released."
42
+ * > — https://developer.android.com/media/media3/session/background-playback
43
+ *
44
+ * The practical cost of getting it backwards was that the session died
45
+ * with the Activity, so "hide the player" and "shut the player down"
46
+ * were the same verb, and a mini player could not exist. The session now
47
+ * lives here, is released here, and outlives any UI.
48
+ *
49
+ * (The docblock's other claim — that the mpv pointer lives "in the
50
+ * activity" — was wrong even before V20. It lives in C++, process-global
51
+ * as `g_mpv`, and is mirrored by [PlaybackHost].)
52
+ *
53
+ * ## The engine is process-global, so no IPC is needed
54
+ *
55
+ * Media3 separates the session server from its UI with `MediaController`
56
+ * because they may be in different processes. Here they are always in
57
+ * one process, and the engine is a C++ global
58
+ * (`native_state.h:13`) reached through the [MPVLib] singleton. So this
59
+ * service issues transport commands directly via [PlaybackHost.handle()]
60
+ * rather than going through a controller indirection, and same-process
61
+ * callers reach it through [instance]. Media3's own session demo has the
62
+ * same shape: `MainActivity` + `PlayerActivity` + `PlaybackService`, with
63
+ * the service owning the player and session.
64
+ *
65
+ * ## Why the notification buttons now work
66
+ *
67
+ * The previous handlers were:
68
+ *
69
+ * ```
70
+ * ACTION_SKIP_NEXT -> Log.d(TAG, "… (MediaSession is the source of truth)")
71
+ * ACTION_SKIP_PREV -> Log.d(TAG, "… (MediaSession is the source of truth)")
72
+ * ```
73
+ *
74
+ * and a play/pause handler that flipped a cached boolean and rebuilt the
75
+ * notification without touching the engine. Two visible buttons and one
76
+ * visible transport control that did nothing. There was no ordering in
77
+ * which those were correct — the MediaStyle may or may not have routed
78
+ * the tap to the session instead, which is exactly the ambiguity that
79
+ * makes a control untrustworthy. Now every button maps to a real
80
+ * command, and [PlaybackStateCompat.ACTION_SEEK_TO] is advertised so the
81
+ * notification's progress bar is actually seekable.
54
82
  */
55
83
  class MediaPlaybackService : Service() {
56
84
 
@@ -66,9 +94,10 @@ class MediaPlaybackService : Service() {
66
94
  const val ACTION_PLAY_PAUSE = "com.simba.player.MEDIA_PLAYBACK_PLAY_PAUSE"
67
95
  const val ACTION_SKIP_NEXT = "com.simba.player.MEDIA_PLAYBACK_SKIP_NEXT"
68
96
  const val ACTION_SKIP_PREV = "com.simba.player.MEDIA_PLAYBACK_SKIP_PREV"
97
+ const val ACTION_SEEK_TO = "com.simba.player.MEDIA_PLAYBACK_SEEK_TO"
69
98
 
70
99
  // Intent extras (kept in sync with PlayerActivity's
71
- // [buildStartIntent] helper).
100
+ // [buildMediaPlaybackServiceIntent] helper).
72
101
  const val EXTRA_TITLE = "title"
73
102
  const val EXTRA_ARTIST = "artist"
74
103
  const val EXTRA_ALBUM = "album"
@@ -76,6 +105,12 @@ class MediaPlaybackService : Service() {
76
105
  const val EXTRA_POSITION_MS = "positionMs"
77
106
  const val EXTRA_DURATION_MS = "durationMs"
78
107
  const val EXTRA_IS_PLAYING = "isPlaying"
108
+ /**
109
+ * Retained for wire compatibility with an already-installed
110
+ * 1.x consumer that still puts a token in the start intent. The
111
+ * service ignores it — it owns the session now and publishes its
112
+ * own token to the notification.
113
+ */
79
114
  const val EXTRA_SESSION_TOKEN = "sessionToken"
80
115
 
81
116
  // Notification action indices (compact view ordering)
@@ -86,8 +121,44 @@ class MediaPlaybackService : Service() {
86
121
  @Volatile
87
122
  private var isRunning = false
88
123
 
124
+ /**
125
+ * The running instance, for same-process callers.
126
+ *
127
+ * This is a convenience handle, not an ownership mechanism: the
128
+ * session and the notification are created and released by the
129
+ * Service's own lifecycle regardless of who holds a reference.
130
+ * It mirrors the existing `currentActivityIsPlayer` pattern used
131
+ * elsewhere in this library.
132
+ */
133
+ @Volatile
134
+ private var instance: MediaPlaybackService? = null
135
+
89
136
  fun isRunning(): Boolean = isRunning
90
137
 
138
+ /**
139
+ * Publish a playback state to the session, if the service is up.
140
+ *
141
+ * Callers are UI. If the service is not running there is no
142
+ * session to publish to and no playback to describe, so this is a
143
+ * deliberate no-op rather than a queued write — a UI must never
144
+ * be the thing that resurrects a torn-down session.
145
+ */
146
+ fun publishState(playing: Boolean, state: Int = PlaybackStateCompat.STATE_PLAYING) {
147
+ instance?.publishPlaybackState(playing, state)
148
+ }
149
+
150
+ /** Publish metadata to the session and refresh the notification. */
151
+ fun publishMetadata(
152
+ title: String,
153
+ artist: String,
154
+ album: String,
155
+ artworkPath: String,
156
+ mediaUri: String,
157
+ displaySubtitle: String,
158
+ ) {
159
+ instance?.applyMetadata(title, artist, album, artworkPath, mediaUri, displaySubtitle)
160
+ }
161
+
91
162
  /**
92
163
  * Build a [PendingIntent] for a notification action targeting
93
164
  * this service. FLAG_IMMUTABLE is mandatory on API 31+ for
@@ -106,9 +177,9 @@ class MediaPlaybackService : Service() {
106
177
  }
107
178
 
108
179
  /**
109
- * Build a PendingIntent that opens `PlayerActivity`. Used
180
+ * Build a [PendingIntent] that opens `PlayerActivity`. Used
110
181
  * when the user taps the notification body — returns them
111
- * to the player if it's still alive, or launches a fresh
182
+ * to the player if its task is still alive, or launches a fresh
112
183
  * instance otherwise.
113
184
  */
114
185
  private fun buildContentIntent(context: Context): PendingIntent {
@@ -129,6 +200,12 @@ class MediaPlaybackService : Service() {
129
200
 
130
201
  private lateinit var notificationManager: NotificationManager
131
202
 
203
+ /**
204
+ * V20 Phase B: the session is created here and released in this
205
+ * service's `onDestroy`, not in an Activity's.
206
+ */
207
+ private var mediaSession: MediaSessionCompat? = null
208
+
132
209
  // Cached metadata for the latest notification rebuild.
133
210
  private var currentTitle: String = "Simba Player"
134
211
  private var currentArtist: String = ""
@@ -137,59 +214,232 @@ class MediaPlaybackService : Service() {
137
214
  private var currentPosition: Long = 0L
138
215
  private var currentDuration: Long = 0L
139
216
  private var isCurrentlyPlaying: Boolean = true
140
- private var sessionToken: MediaSessionCompat.Token? = null
141
217
 
142
218
  // ── Lifecycle ──────────────────────────────────────────────────────────
143
219
 
144
220
  override fun onCreate() {
145
221
  super.onCreate()
222
+ instance = this
146
223
  notificationManager = getSystemService(NotificationManager::class.java)
147
224
  createNotificationChannel()
148
- Log.i(TAG, "MediaPlaybackService created")
225
+ createMediaSession()
226
+ Log.i(TAG, "MediaPlaybackService created (session owned by service)")
149
227
  }
150
228
 
151
229
  override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
152
230
  when (intent?.action) {
153
231
  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.
232
+ ACTION_STOP -> handleStop()
233
+ // Every one of these now issues a real engine command. They
234
+ // were previously a boolean flip and two log statements.
165
235
  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)")
236
+ ACTION_SKIP_NEXT -> handleSkipNext()
237
+ ACTION_SKIP_PREV -> handleSkipPrevious()
238
+ ACTION_SEEK_TO -> handleSeekTo(intent)
168
239
  else -> handleStart(intent)
169
240
  }
170
241
  return START_REDELIVER_INTENT
171
242
  }
172
243
 
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
244
  override fun onBind(intent: Intent?): IBinder? = null
185
245
 
186
246
  override fun onDestroy() {
247
+ // Media3 puts player + session release in the *service's*
248
+ // onDestroy. Doing it in an Activity's is what tied the session's
249
+ // lifetime to a window.
250
+ releaseMediaSession()
187
251
  isRunning = false
252
+ instance = null
188
253
  notificationManager.cancel(NOTIFICATION_ID)
189
254
  Log.i(TAG, "MediaPlaybackService destroyed")
190
255
  super.onDestroy()
191
256
  }
192
257
 
258
+ // ── Session ownership ──────────────────────────────────────────────────
259
+
260
+ /**
261
+ * The full transport set, issued against the process-global engine.
262
+ *
263
+ * Every handler reads the handle at the moment of use via
264
+ * [PlaybackHost] rather than caching it — a cached copy is what let
265
+ * an Activity's controls go silently dead after a destroy/re-create.
266
+ */
267
+ private fun createMediaSession() {
268
+ val callback = object : MediaSessionCompat.Callback() {
269
+ override fun onPlay() = command("onPlay") {
270
+ MPVLib.nativePlay(ptr())
271
+ publishPlaybackState(playing = true)
272
+ }
273
+
274
+ override fun onPause() = command("onPause") {
275
+ MPVLib.nativePause(ptr())
276
+ publishPlaybackState(playing = false)
277
+ }
278
+
279
+ override fun onStop() = command("onStop") {
280
+ MPVLib.nativeStop(ptr())
281
+ publishPlaybackState(playing = false, state = PlaybackStateCompat.STATE_STOPPED)
282
+ }
283
+
284
+ override fun onSkipToNext() = command("onSkipToNext") {
285
+ MPVLib.nativePlaylistNext(ptr())
286
+ publishPlaybackState(playing = true)
287
+ }
288
+
289
+ override fun onSkipToPrevious() = command("onSkipToPrevious") {
290
+ MPVLib.nativePlaylistPrev(ptr())
291
+ publishPlaybackState(playing = true)
292
+ }
293
+
294
+ override fun onSeekTo(pos: Long) = command("onSeekTo($pos)") {
295
+ if (pos >= 0L) MPVLib.nativeSeek(ptr(), pos.toDouble() / 1000.0)
296
+ }
297
+ }
298
+
299
+ val session = MediaSessionCompat(this, TAG).apply {
300
+ setFlags(
301
+ MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS or
302
+ MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS,
303
+ )
304
+ setCallback(callback)
305
+ // Tapping the lock-screen widget should surface the player.
306
+ val activityIntent = Intent().apply {
307
+ setClassName(this@MediaPlaybackService, "com.simba.player.PlayerActivity")
308
+ flags = Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP
309
+ }
310
+ setSessionActivity(
311
+ PendingIntent.getActivity(
312
+ this@MediaPlaybackService,
313
+ 0,
314
+ activityIntent,
315
+ PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
316
+ ),
317
+ )
318
+ isActive = true
319
+ }
320
+ mediaSession = session
321
+ publishPlaybackState(playing = true)
322
+ Log.i(TAG, "MediaSession created and owned by the service")
323
+ }
324
+
325
+ private fun releaseMediaSession() {
326
+ val session = mediaSession ?: return
327
+ try {
328
+ session.isActive = false
329
+ session.release()
330
+ Log.i(TAG, "MediaSession released")
331
+ } catch (e: Exception) {
332
+ Log.w(TAG, "releaseMediaSession: ${e.message}", e)
333
+ } finally {
334
+ mediaSession = null
335
+ }
336
+ }
337
+
338
+ /**
339
+ * Run [block] against the engine, or explain why it could not run.
340
+ *
341
+ * A transport command that silently does nothing is the exact defect
342
+ * this class used to contain, so "no engine" is logged rather than
343
+ * swallowed.
344
+ */
345
+ private inline fun command(label: String, block: () -> Unit) {
346
+ if (ptr() == 0L) {
347
+ Log.w(TAG, "MediaSession.$label ignored: no engine handle")
348
+ return
349
+ }
350
+ try {
351
+ block()
352
+ } catch (e: Exception) {
353
+ Log.w(TAG, "MediaSession.$label threw ${e.message}", e)
354
+ }
355
+ }
356
+
357
+ private fun ptr(): Long = PlaybackHost.handle()
358
+
359
+ private fun enginePropertyMs(name: String): Long {
360
+ val handle = ptr()
361
+ if (handle == 0L) return 0L
362
+ return try {
363
+ MPVLib.nativeGetProperty(handle, name).trim().toDoubleOrNull()?.times(1000.0)?.toLong() ?: 0L
364
+ } catch (_: Exception) {
365
+ 0L
366
+ }
367
+ }
368
+
369
+ private fun engineProperty(name: String): String {
370
+ val handle = ptr()
371
+ if (handle == 0L) return ""
372
+ return try {
373
+ MPVLib.nativeGetProperty(handle, name).trim()
374
+ } catch (_: Exception) {
375
+ ""
376
+ }
377
+ }
378
+
379
+ /** Push the current transport state into the session. */
380
+ private fun publishPlaybackState(
381
+ playing: Boolean,
382
+ state: Int = if (playing) PlaybackStateCompat.STATE_PLAYING else PlaybackStateCompat.STATE_PAUSED,
383
+ ) {
384
+ val session = mediaSession ?: return
385
+ val positionMs = enginePropertyMs("time-pos")
386
+ val builder = PlaybackStateCompat.Builder()
387
+ .setActions(
388
+ PlaybackStateCompat.ACTION_PLAY or
389
+ PlaybackStateCompat.ACTION_PAUSE or
390
+ PlaybackStateCompat.ACTION_PLAY_PAUSE or
391
+ PlaybackStateCompat.ACTION_STOP or
392
+ PlaybackStateCompat.ACTION_SKIP_TO_NEXT or
393
+ PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS or
394
+ // Advertised, so the notification's progress bar is
395
+ // genuinely seekable rather than a decoration.
396
+ PlaybackStateCompat.ACTION_SEEK_TO,
397
+ )
398
+ .setState(state, positionMs, 1.0f)
399
+ session.setPlaybackState(builder.build())
400
+
401
+ // Keep the notification's own cache in step so its progress bar
402
+ // and play/pause glyph reflect reality rather than optimism.
403
+ currentPosition = positionMs
404
+ currentDuration = enginePropertyMs("duration")
405
+ isCurrentlyPlaying = playing
406
+ }
407
+
408
+ private fun applyMetadata(
409
+ title: String,
410
+ artist: String,
411
+ album: String,
412
+ artworkPath: String,
413
+ mediaUri: String,
414
+ displaySubtitle: String,
415
+ ) {
416
+ if (title.isNotBlank()) currentTitle = title
417
+ currentArtist = artist
418
+ currentAlbum = album
419
+ currentArtworkPath = artworkPath
420
+
421
+ val session = mediaSession ?: return
422
+ val durationMs = enginePropertyMs("duration")
423
+ val builder = MediaMetadataCompat.Builder()
424
+ .putString(MediaMetadataCompat.METADATA_KEY_TITLE, currentTitle)
425
+ .putString(MediaMetadataCompat.METADATA_KEY_DISPLAY_TITLE, currentTitle)
426
+ if (currentArtist.isNotBlank()) {
427
+ builder.putString(MediaMetadataCompat.METADATA_KEY_ARTIST, currentArtist)
428
+ }
429
+ if (currentAlbum.isNotBlank()) {
430
+ builder.putString(MediaMetadataCompat.METADATA_KEY_ALBUM, currentAlbum)
431
+ }
432
+ if (displaySubtitle.isNotBlank()) {
433
+ builder.putString(MediaMetadataCompat.METADATA_KEY_DISPLAY_SUBTITLE, displaySubtitle)
434
+ }
435
+ if (mediaUri.isNotBlank()) {
436
+ builder.putString(MediaMetadataCompat.METADATA_KEY_MEDIA_URI, mediaUri)
437
+ }
438
+ if (durationMs > 0L) builder.putLong(MediaMetadataCompat.METADATA_KEY_DURATION, durationMs)
439
+ session.setMetadata(builder.build())
440
+ notificationManager.notify(NOTIFICATION_ID, buildNotification())
441
+ }
442
+
193
443
  // ── Action Handlers ────────────────────────────────────────────────────
194
444
 
195
445
  private fun handleStart(intent: Intent?) {
@@ -201,14 +451,9 @@ class MediaPlaybackService : Service() {
201
451
  currentPosition = extras?.getLong(EXTRA_POSITION_MS, 0L) ?: 0L
202
452
  currentDuration = extras?.getLong(EXTRA_DURATION_MS, 0L) ?: 0L
203
453
  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
454
  isRunning = true
210
- val notification = buildNotification()
211
- startForeground(NOTIFICATION_ID, notification)
455
+ applyMetadata(currentTitle, currentArtist, currentAlbum, currentArtworkPath, "", "")
456
+ startForeground(NOTIFICATION_ID, buildNotification())
212
457
  Log.i(
213
458
  TAG,
214
459
  "Media playback started: title='$currentTitle' artist='$currentArtist' playing=$isCurrentlyPlaying",
@@ -228,6 +473,81 @@ class MediaPlaybackService : Service() {
228
473
  Log.d(TAG, "Media playback updated: position=$currentPosition playing=$isCurrentlyPlaying")
229
474
  }
230
475
 
476
+ private fun handleStop() {
477
+ command("notification-stop") {
478
+ if (ptr() != 0L) MPVLib.nativeStop(ptr())
479
+ }
480
+ publishPlaybackState(playing = false, state = PlaybackStateCompat.STATE_STOPPED)
481
+ stopForeground(STOP_FOREGROUND_REMOVE)
482
+ stopSelf()
483
+ }
484
+
485
+ private fun handlePlayPause() {
486
+ val handle = ptr()
487
+ if (handle == 0L) {
488
+ Log.w(TAG, "ACTION_PLAY_PAUSE ignored: no engine handle")
489
+ return
490
+ }
491
+ val playing = !isCurrentlyPlaying
492
+ try {
493
+ if (playing) MPVLib.nativePlay(handle) else MPVLib.nativePause(handle)
494
+ } catch (e: Exception) {
495
+ Log.w(TAG, "ACTION_PLAY_PAUSE: command threw ${e.message}", e)
496
+ return
497
+ }
498
+ // State is published *after* the command, so the glyph reflects
499
+ // what the engine was actually told to do — not what we hoped.
500
+ publishPlaybackState(playing)
501
+ notificationManager.notify(NOTIFICATION_ID, buildNotification())
502
+ }
503
+
504
+ private fun handleSkipNext() {
505
+ if (ptr() == 0L) {
506
+ Log.w(TAG, "ACTION_SKIP_NEXT ignored: no engine handle")
507
+ return
508
+ }
509
+ try {
510
+ MPVLib.nativePlaylistNext(ptr())
511
+ } catch (e: Exception) {
512
+ Log.w(TAG, "ACTION_SKIP_NEXT: ${e.message}", e)
513
+ return
514
+ }
515
+ publishPlaybackState(playing = true)
516
+ notificationManager.notify(NOTIFICATION_ID, buildNotification())
517
+ }
518
+
519
+ private fun handleSkipPrevious() {
520
+ if (ptr() == 0L) {
521
+ Log.w(TAG, "ACTION_SKIP_PREV ignored: no engine handle")
522
+ return
523
+ }
524
+ try {
525
+ MPVLib.nativePlaylistPrev(ptr())
526
+ } catch (e: Exception) {
527
+ Log.w(TAG, "ACTION_SKIP_PREV: ${e.message}", e)
528
+ return
529
+ }
530
+ publishPlaybackState(playing = true)
531
+ notificationManager.notify(NOTIFICATION_ID, buildNotification())
532
+ }
533
+
534
+ private fun handleSeekTo(intent: Intent) {
535
+ val positionMs = intent.getLongExtra(EXTRA_POSITION_MS, -1L)
536
+ val handle = ptr()
537
+ if (handle == 0L || positionMs < 0L) {
538
+ Log.w(TAG, "ACTION_SEEK_TO ignored (handle=$handle, pos=$positionMs)")
539
+ return
540
+ }
541
+ try {
542
+ MPVLib.nativeSeek(handle, positionMs.toDouble() / 1000.0)
543
+ } catch (e: Exception) {
544
+ Log.w(TAG, "ACTION_SEEK_TO: ${e.message}", e)
545
+ return
546
+ }
547
+ publishPlaybackState(isCurrentlyPlaying)
548
+ notificationManager.notify(NOTIFICATION_ID, buildNotification())
549
+ }
550
+
231
551
  // ── Notification Channel (Android 8+) ──────────────────────────────────
232
552
 
233
553
  private fun createNotificationChannel() {
@@ -283,19 +603,15 @@ class MediaPlaybackService : Service() {
283
603
  .setSilent(true)
284
604
  .setOnlyAlertOnce(true)
285
605
 
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
606
+ // MediaStyle points at *this service's own* session — no token
607
+ // has to be handed in by an Activity any more.
608
+ val session = mediaSession
293
609
  val mediaStyle = androidx.media.app.NotificationCompat.MediaStyle()
294
610
  .setShowActionsInCompactView(INDEX_PLAY, INDEX_NEXT, INDEX_PREV)
295
611
  .setShowCancelButton(true)
296
612
  .setCancelButtonIntent(buildActionIntent(this, ACTION_STOP))
297
- if (token != null) {
298
- mediaStyle.setMediaSession(token)
613
+ if (session != null) {
614
+ mediaStyle.setMediaSession(session.sessionToken)
299
615
  }
300
616
  builder.setStyle(mediaStyle)
301
617
 
@@ -317,9 +633,14 @@ class MediaPlaybackService : Service() {
317
633
  buildActionIntent(this, ACTION_STOP),
318
634
  )
319
635
 
320
- // Progress bar (seekable on Android 12+ when the session
321
- // exposes SEEK_TO; not used here yet — Phase 20 wires it).
636
+ // Progress bar. Seekable now, because the session advertises
637
+ // ACTION_SEEK_TO and ACTION_SEEK_TO dispatches a real command.
322
638
  if (currentDuration > 0L) {
639
+ builder.addAction(
640
+ android.R.drawable.ic_media_play,
641
+ "Seek",
642
+ buildSeekIntent(currentPosition),
643
+ )
323
644
  builder.setProgress(
324
645
  currentDuration.toInt(),
325
646
  currentPosition.toInt(),
@@ -330,6 +651,19 @@ class MediaPlaybackService : Service() {
330
651
  return builder.build()
331
652
  }
332
653
 
654
+ private fun buildSeekIntent(positionMs: Long): PendingIntent {
655
+ val intent = Intent(this, MediaPlaybackService::class.java).apply {
656
+ action = ACTION_SEEK_TO
657
+ putExtra(EXTRA_POSITION_MS, positionMs)
658
+ }
659
+ return PendingIntent.getService(
660
+ this,
661
+ (ACTION_SEEK_TO + positionMs).hashCode(),
662
+ intent,
663
+ PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
664
+ )
665
+ }
666
+
333
667
  // ── Artwork Loading ────────────────────────────────────────────────────
334
668
 
335
669
  private fun loadArtworkBitmap(path: String): Bitmap? {
@@ -355,31 +689,4 @@ class MediaPlaybackService : Service() {
355
689
  null
356
690
  }
357
691
  }
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
- }
692
+ }