@octane-xplat/audio 0.0.0-nightly.g14544fe

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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2026 Alec Larson
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,69 @@
1
+ # `@octane-xplat/audio`
2
+
3
+ ```sh
4
+ pnpm add @octane-xplat/audio
5
+ ```
6
+
7
+ Long-form audio playback for Octane xplat apps — a queue player, not a
8
+ sound-effect bank. iOS uses `AVPlayer`/`AVAudioSession` (interruption
9
+ handling included) and Android uses a package-owned Media3 playback service.
10
+ macOS uses a package-owned AVPlayer bridge. Web uses an
11
+ `HTMLAudioElement` plus the Media Session API for system controls.
12
+
13
+ ```ts
14
+ import { createAudioPlayer } from '@octane-xplat/audio'
15
+
16
+ const player = createAudioPlayer()
17
+ await player.setQueue([{ id: 'ep1', source: 'https://example.com/ep1.mp3' }])
18
+ await player.play()
19
+
20
+ const off = player.subscribe((snapshot) => {
21
+ // { state, currentTime, duration } — poll or subscribe, your choice
22
+ })
23
+ ```
24
+
25
+ Playback features vary by target and runtime state, so call
26
+ `capabilities()` before promising behavior like lock-screen controls. It
27
+ reports `supported`, `backgroundPlayback`, `systemControls`,
28
+ `userGestureRequired`, and `interruptions`. The `macos` package condition
29
+ selects the desktop bridge without importing mobile implementations. Rebuild
30
+ the macOS app after installing this package. macOS reports system controls and
31
+ interruption recovery as unavailable; a missing bridge reports `supported: false`.
32
+
33
+ ```ts
34
+ // Continue with the player created above.
35
+ const capabilities = player.capabilities()
36
+ console.log(capabilities.backgroundPlayback, capabilities.systemControls)
37
+ off()
38
+ player.dispose()
39
+ ```
40
+
41
+ On macOS, use an absolute local path, `file:` URL, or HTTP(S) URL. Queue
42
+ replacement rejects obsolete pending loads and stops the previous item.
43
+ Malformed media, network errors, reported output errors, and loading or
44
+ buffering stalled for 30 seconds become terminal errors. A new queue can retry;
45
+ disposal stops playback and notifications. Position, duration, and seek use
46
+ seconds. Real audible playback remains a separate qualification gate.
47
+
48
+ ```ts
49
+ import { createAudioPlayer } from '@octane-xplat/audio'
50
+
51
+ export async function playTrack(source: string) {
52
+ const player = createAudioPlayer()
53
+ try {
54
+ await player.setQueue([{ id: 'track', source }])
55
+ await player.play()
56
+ await player.seek(2.5)
57
+ await player.pause()
58
+ } finally {
59
+ player.dispose()
60
+ }
61
+ }
62
+ ```
63
+
64
+ For short UI sounds use [`@octane-xplat/sounds`](../sounds/README.md).
65
+
66
+ Guide: [Media services](../../docs/platform/media-services.md); per-target
67
+ availability: [platform notes](../../.agents/docs/notes/platform-notes.md). Exercised by
68
+ the harness `MediaServices` screen
69
+ ([`packages/app/src/MediaServices.tsrx`](../app/src/MediaServices.tsrx)).
package/package.json ADDED
@@ -0,0 +1,99 @@
1
+ {
2
+ "name": "@octane-xplat/audio",
3
+ "version": "0.0.0-nightly.g14544fe",
4
+ "description": "Long-form audio playback for Octane xplat",
5
+ "keywords": [
6
+ "android",
7
+ "audio",
8
+ "audio-player",
9
+ "cross-platform",
10
+ "ios",
11
+ "music",
12
+ "nativescript",
13
+ "octane",
14
+ "playback",
15
+ "web",
16
+ "xplat"
17
+ ],
18
+ "homepage": "https://github.com/octane-xplat/octane-xplat/tree/main/packages/audio",
19
+ "license": "MIT",
20
+ "repository": {
21
+ "type": "git",
22
+ "url": "https://github.com/octane-xplat/octane-xplat",
23
+ "directory": "packages/audio"
24
+ },
25
+ "files": [
26
+ "types",
27
+ "src",
28
+ "platforms",
29
+ "!src/**/*.test.*",
30
+ "!src/**/*.spec.*"
31
+ ],
32
+ "type": "module",
33
+ "exports": {
34
+ ".": {
35
+ "macos": {
36
+ "types": "./types/index.d.ts",
37
+ "default": "./src/index.macos.ts"
38
+ },
39
+ "types": "./types/index.d.ts",
40
+ "web": "./src/index.web.ts",
41
+ "native": "./src/index.ts",
42
+ "default": "./src/index.ts"
43
+ }
44
+ },
45
+ "publishConfig": {
46
+ "access": "public"
47
+ },
48
+ "dependencies": {
49
+ "@octane-xplat/platform": "0.0.0-nightly.g14544fe"
50
+ },
51
+ "devDependencies": {
52
+ "@nativescript-community/octane": "0.2.5",
53
+ "@nativescript/core": "9.1.3",
54
+ "@octanejs/vite-plugin": "0.1.61",
55
+ "octane": "0.11.0",
56
+ "tsrx-typegen": "0.3.0",
57
+ "typescript": "5.9.3",
58
+ "vite": "8.3.0"
59
+ },
60
+ "peerDependencies": {
61
+ "@nativescript-community/octane": ">=0.2.1 <1",
62
+ "@nativescript/core": ">=9.1.0 <10",
63
+ "octane": ">=0.6.3 <1"
64
+ },
65
+ "peerDependenciesMeta": {
66
+ "@nativescript-community/octane": {
67
+ "optional": true
68
+ },
69
+ "@nativescript/core": {
70
+ "optional": true
71
+ },
72
+ "octane": {
73
+ "optional": true
74
+ }
75
+ },
76
+ "nativescript": {
77
+ "platforms": {
78
+ "android": "9.1.0",
79
+ "ios": "9.1.0"
80
+ }
81
+ },
82
+ "xplat": {
83
+ "macos": {
84
+ "frameworks": [
85
+ "Foundation",
86
+ "AVFoundation",
87
+ "CoreMedia"
88
+ ]
89
+ }
90
+ },
91
+ "scripts": {
92
+ "test": "node --test tests/*.test.mjs",
93
+ "typegen": "tsc -p tsconfig.types.json",
94
+ "test:packed": "node tests/packed-consumer.mjs",
95
+ "pack:check": "tsrx-typegen --pack-check",
96
+ "test:macos-runtime": "node tests/packed-consumer.mjs --macos-runtime",
97
+ "typecheck": "tsc --noEmit --strict --target esnext --module esnext --moduleResolution bundler --skipLibCheck src/audio.macos.ts"
98
+ }
99
+ }
@@ -0,0 +1,15 @@
1
+ <manifest xmlns:android="http://schemas.android.com/apk/res/android">
2
+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
3
+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK" />
4
+
5
+ <application>
6
+ <service
7
+ android:name="com.xplat.audio.AudioPlaybackService"
8
+ android:exported="true"
9
+ android:foregroundServiceType="mediaPlayback">
10
+ <intent-filter>
11
+ <action android:name="androidx.media3.session.MediaSessionService" />
12
+ </intent-filter>
13
+ </service>
14
+ </application>
15
+ </manifest>
Binary file
@@ -0,0 +1,8 @@
1
+ repositories {
2
+ mavenCentral()
3
+ }
4
+
5
+ dependencies {
6
+ implementation "androidx.media3:media3-exoplayer:1.9.3"
7
+ implementation "androidx.media3:media3-session:1.9.3"
8
+ }
@@ -0,0 +1,58 @@
1
+ package com.xplat.audio;
2
+
3
+ import android.content.Context;
4
+ import android.content.Intent;
5
+ import android.util.Log;
6
+
7
+ /** Commands cross the JS/service boundary as intents so they remain ordered. */
8
+ public final class AudioBridge {
9
+ public static final String ACTION_QUEUE = "com.xplat.audio.QUEUE";
10
+ public static final String ACTION_PLAY = "com.xplat.audio.PLAY";
11
+ public static final String ACTION_PAUSE = "com.xplat.audio.PAUSE";
12
+ public static final String ACTION_SEEK = "com.xplat.audio.SEEK";
13
+ public static final String ACTION_RELEASE = "com.xplat.audio.RELEASE";
14
+ private static final String TAG = "XplatAudio";
15
+ // The service is exported for the Media3 session — command intents are
16
+ // accepted only when they carry this process-local token, which a foreign
17
+ // app cannot observe or forge.
18
+ private static final String COMMAND_TOKEN = java.util.UUID.randomUUID().toString();
19
+ private static volatile String snapshot = "{\"state\":\"idle\",\"currentTime\":0,\"duration\":0}";
20
+ private static volatile String pendingQueue;
21
+
22
+ private AudioBridge() {}
23
+
24
+ public static void dispatch(Context context, String action, String payload, int index, double seconds) {
25
+ Intent intent = new Intent(context.getApplicationContext(), AudioPlaybackService.class);
26
+ intent.setAction(action);
27
+ intent.putExtra("commandToken", COMMAND_TOKEN);
28
+ // The queue JSON can exceed the ~1MB Binder extra limit — hand it to
29
+ // the service in-process and keep the intent small.
30
+ if (payload != null && ACTION_QUEUE.equals(action)) pendingQueue = payload;
31
+ intent.putExtra("index", index);
32
+ intent.putExtra("seconds", seconds);
33
+ try {
34
+ context.getApplicationContext().startService(intent);
35
+ } catch (RuntimeException failure) {
36
+ // A JS-initiated command while the app is backgrounded throws
37
+ // IllegalStateException — surface it through snapshot.error and
38
+ // rethrow so the caller's promise rejects.
39
+ pendingQueue = null;
40
+ Log.e(TAG, "Audio command dispatch failed", failure);
41
+ publish("{\"state\":\"error\",\"currentTime\":0,\"duration\":0,\"error\":\"audio command dispatch failed\"}");
42
+ throw failure;
43
+ }
44
+ }
45
+
46
+ static boolean isCommandIntent(Intent intent) {
47
+ return intent != null && COMMAND_TOKEN.equals(intent.getStringExtra("commandToken"));
48
+ }
49
+
50
+ static String takeQueue() {
51
+ String queue = pendingQueue;
52
+ pendingQueue = null;
53
+ return queue;
54
+ }
55
+
56
+ public static void publish(String value) { snapshot = value; }
57
+ public static String snapshot() { return snapshot; }
58
+ }
@@ -0,0 +1,122 @@
1
+ package com.xplat.audio;
2
+
3
+ import android.content.Intent;
4
+ import android.net.Uri;
5
+ import java.io.File;
6
+ import android.os.IBinder;
7
+ import android.util.Log;
8
+
9
+ import androidx.media3.common.AudioAttributes;
10
+ import androidx.media3.common.MediaItem;
11
+ import androidx.media3.common.MediaMetadata;
12
+ import androidx.media3.common.PlaybackException;
13
+ import androidx.media3.common.Player;
14
+ import androidx.media3.exoplayer.ExoPlayer;
15
+ import androidx.media3.session.MediaSession;
16
+ import androidx.media3.session.MediaSessionService;
17
+
18
+ import org.json.JSONArray;
19
+ import org.json.JSONObject;
20
+
21
+ public final class AudioPlaybackService extends MediaSessionService {
22
+ private static final String TAG = "XplatAudio";
23
+ private ExoPlayer player;
24
+ private MediaSession session;
25
+ private Player.Listener listener;
26
+ private String error;
27
+
28
+ @Override public void onCreate() {
29
+ super.onCreate();
30
+ player = new ExoPlayer.Builder(this).build();
31
+ player.setAudioAttributes(AudioAttributes.DEFAULT, true);
32
+ listener = new Player.Listener() {
33
+ @Override public void onEvents(Player p, Player.Events events) { publishSnapshot(); }
34
+ @Override public void onPlayerError(PlaybackException exception) {
35
+ error = exception.getMessage();
36
+ publishSnapshot();
37
+ }
38
+ };
39
+ player.addListener(listener);
40
+ session = new MediaSession.Builder(this, player).build();
41
+ publishSnapshot();
42
+ }
43
+
44
+ @Override public MediaSession onGetSession(MediaSession.ControllerInfo controllerInfo) { return session; }
45
+
46
+ @Override public int onStartCommand(Intent intent, int flags, int startId) {
47
+ int result = super.onStartCommand(intent, flags, startId);
48
+ if (intent == null || intent.getAction() == null) return result;
49
+ // com.xplat.audio.* commands execute only for this app's in-process
50
+ // bridge — the exported service is reachable by any installed app, so
51
+ // foreign command intents without the process token are dropped.
52
+ if (intent.getAction().startsWith("com.xplat.audio.") && !AudioBridge.isCommandIntent(intent)) {
53
+ return result;
54
+ }
55
+
56
+ try {
57
+ switch (intent.getAction()) {
58
+ case AudioBridge.ACTION_QUEUE:
59
+ setQueue(AudioBridge.takeQueue(), intent.getIntExtra("index", 0));
60
+ break;
61
+ case AudioBridge.ACTION_PLAY: player.play(); break;
62
+ case AudioBridge.ACTION_PAUSE: player.pause(); break;
63
+ case AudioBridge.ACTION_SEEK: player.seekTo((long) (intent.getDoubleExtra("seconds", 0) * 1000)); break;
64
+ case AudioBridge.ACTION_RELEASE:
65
+ player.stop();
66
+ player.clearMediaItems();
67
+ stopSelf();
68
+ break;
69
+ }
70
+ } catch (Exception cause) {
71
+ Log.e(TAG, "Audio command failed", cause);
72
+ error = cause.getMessage();
73
+ publishSnapshot();
74
+ }
75
+ return result;
76
+ }
77
+
78
+ private void setQueue(String encoded, int startAt) throws Exception {
79
+ JSONArray queue = new JSONArray(encoded == null ? "[]" : encoded);
80
+ player.clearMediaItems();
81
+ error = null;
82
+ for (int i = 0; i < queue.length(); i++) {
83
+ JSONObject track = queue.getJSONObject(i);
84
+ String source = track.getString("source");
85
+ MediaMetadata metadata = new MediaMetadata.Builder()
86
+ .setTitle(track.optString("title", track.optString("id", "")))
87
+ .setArtist(track.optString("artist", ""))
88
+ .setAlbumTitle(track.optString("album", ""))
89
+ .build();
90
+ Uri uri = source.startsWith("/") ? Uri.fromFile(new File(source)) : Uri.parse(source);
91
+ player.addMediaItem(new MediaItem.Builder().setUri(uri).setMediaMetadata(metadata).build());
92
+ }
93
+ if (queue.length() > 0) player.seekTo(Math.max(0, Math.min(startAt, queue.length() - 1)), 0);
94
+ player.prepare();
95
+ publishSnapshot();
96
+ }
97
+
98
+ private void publishSnapshot() {
99
+ try {
100
+ JSONObject value = new JSONObject();
101
+ int index = player == null ? -1 : player.getCurrentMediaItemIndex();
102
+ value.put("state", error != null ? "error" : player == null || player.getMediaItemCount() == 0 ? "idle" : player.getPlaybackState() == Player.STATE_ENDED ? "ended" : player.isPlaying() ? "playing" : player.getPlaybackState() == Player.STATE_BUFFERING ? "loading" : "paused");
103
+ value.put("index", index);
104
+ value.put("currentTime", player == null ? 0 : Math.max(0, player.getCurrentPosition()) / 1000.0);
105
+ value.put("duration", player == null || player.getDuration() < 0 ? 0 : player.getDuration() / 1000.0);
106
+ if (error != null) value.put("error", error);
107
+ AudioBridge.publish(value.toString());
108
+ } catch (Exception ignored) { }
109
+ }
110
+
111
+ @Override public void onDestroy() {
112
+ if (player != null) {
113
+ player.removeListener(listener);
114
+ player.release();
115
+ }
116
+ if (session != null) session.release();
117
+ AudioBridge.publish("{\"state\":\"idle\",\"currentTime\":0,\"duration\":0}");
118
+ super.onDestroy();
119
+ }
120
+
121
+ @Override public IBinder onBind(Intent intent) { return super.onBind(intent); }
122
+ }
@@ -0,0 +1,5 @@
1
+ // MediaPlayer.framework supplies MPNowPlayingInfoCenter / MPRemoteCommandCenter
2
+ // and the MPNowPlayingInfoProperty* keys used by the iOS lock-screen transport
3
+ // integration. Without the explicit link, JS symbol lookups fail at runtime
4
+ // (ReferenceError: MPNowPlayingInfoPropertyPlaybackDuration is not defined).
5
+ OTHER_LDFLAGS = $(inherited) -framework "MediaPlayer"
@@ -0,0 +1,12 @@
1
+ #import <Foundation/Foundation.h>
2
+
3
+ // One instance owns one AVPlayer. Calls and notifications run on the host main thread.
4
+ @interface XplatAudioPlayer : NSObject
5
+ - (void)setSource:(NSString *)source;
6
+ - (void)play;
7
+ - (void)pause;
8
+ - (void)seekSeconds:(double)seconds;
9
+ - (NSString *)snapshot;
10
+ - (void)clear;
11
+ - (void)dispose;
12
+ @end
@@ -0,0 +1,161 @@
1
+ #import "XplatAudioPlayer.h"
2
+ #import <AVFoundation/AVFoundation.h>
3
+ #import <math.h>
4
+
5
+ @interface XplatAudioPlayer ()
6
+ @property(nonatomic, strong) AVPlayer *player;
7
+ @property(nonatomic, strong) AVPlayerItem *item;
8
+ @property(nonatomic, strong) NSMutableArray *observers;
9
+ @property(nonatomic, copy) NSString *state;
10
+ @property(nonatomic, copy) NSString *failure;
11
+ @property(nonatomic) BOOL disposed;
12
+ @property(nonatomic) BOOL wantsPlayback;
13
+ @property(nonatomic) NSTimeInterval loadingSince;
14
+ @end
15
+
16
+ @implementation XplatAudioPlayer
17
+ - (instancetype)init {
18
+ if ((self = [super init])) {
19
+ _state = @"idle";
20
+ _observers = [NSMutableArray new];
21
+ }
22
+ return self;
23
+ }
24
+
25
+ - (void)releaseTrack {
26
+ for (id token in self.observers) [[NSNotificationCenter defaultCenter] removeObserver:token];
27
+ [self.observers removeAllObjects];
28
+ [self.player pause];
29
+ [self.item cancelPendingSeeks];
30
+ [self.item.asset cancelLoading];
31
+ [self.player replaceCurrentItemWithPlayerItem:nil];
32
+ self.item = nil;
33
+ self.player = nil;
34
+ self.wantsPlayback = NO;
35
+ self.loadingSince = 0;
36
+ }
37
+
38
+ - (void)fail:(NSString *)message {
39
+ [self releaseTrack];
40
+ self.failure = message.length ? message : @"Audio playback failed";
41
+ self.state = @"error";
42
+ }
43
+
44
+ - (void)setSource:(NSString *)source {
45
+ if (self.disposed) return;
46
+ [self clear];
47
+ NSURL *url = [source hasPrefix:@"/"] ? [NSURL fileURLWithPath:source] : [NSURL URLWithString:source];
48
+ NSString *scheme = url.scheme.lowercaseString;
49
+ if (!url || !([scheme isEqual:@"file"] ||
50
+ (([scheme isEqual:@"http"] || [scheme isEqual:@"https"]) && url.host.length))) {
51
+ [self fail:@"Audio source must be an absolute path, file URL, or HTTP(S) URL"];
52
+ return;
53
+ }
54
+ if (url.isFileURL && ![[NSFileManager defaultManager] isReadableFileAtPath:url.path]) {
55
+ [self fail:@"Audio file is not readable"];
56
+ return;
57
+ }
58
+ self.state = @"loading";
59
+ self.loadingSince = NSProcessInfo.processInfo.systemUptime;
60
+ self.item = [AVPlayerItem playerItemWithURL:url];
61
+ self.player = [AVPlayer playerWithPlayerItem:self.item];
62
+ __weak XplatAudioPlayer *owner = self;
63
+ AVPlayerItem *item = self.item;
64
+ NSNotificationCenter *center = NSNotificationCenter.defaultCenter;
65
+ [self.observers addObject:[center addObserverForName:AVPlayerItemDidPlayToEndTimeNotification
66
+ object:item queue:NSOperationQueue.mainQueue usingBlock:^(NSNotification *note) {
67
+ XplatAudioPlayer *strongOwner = owner;
68
+ if (!strongOwner || strongOwner.disposed || strongOwner.item != note.object) return;
69
+ [strongOwner.player pause];
70
+ strongOwner.wantsPlayback = NO;
71
+ strongOwner.state = @"ended";
72
+ }]];
73
+ [self.observers addObject:[center addObserverForName:AVPlayerItemFailedToPlayToEndTimeNotification
74
+ object:item queue:NSOperationQueue.mainQueue usingBlock:^(NSNotification *note) {
75
+ XplatAudioPlayer *strongOwner = owner;
76
+ if (!strongOwner || strongOwner.disposed || strongOwner.item != note.object) return;
77
+ NSError *error = note.userInfo[AVPlayerItemFailedToPlayToEndTimeErrorKey];
78
+ [strongOwner fail:error.localizedDescription];
79
+ }]];
80
+ }
81
+
82
+ - (void)refresh {
83
+ if (!self.item || self.disposed || [self.state isEqual:@"ended"]) return;
84
+ if (self.item.status == AVPlayerItemStatusFailed || self.player.status == AVPlayerStatusFailed) {
85
+ [self fail:(self.item.error ?: self.player.error).localizedDescription];
86
+ return;
87
+ }
88
+ BOOL waiting = self.item.status != AVPlayerItemStatusReadyToPlay ||
89
+ (self.wantsPlayback && self.player.timeControlStatus != AVPlayerTimeControlStatusPlaying);
90
+ if (waiting) {
91
+ self.state = @"loading";
92
+ NSTimeInterval now = NSProcessInfo.processInfo.systemUptime;
93
+ if (!self.loadingSince) self.loadingSince = now;
94
+ if (now - self.loadingSince >= 30) [self fail:@"Audio loading or buffering timed out"];
95
+ } else {
96
+ self.loadingSince = 0;
97
+ self.state = self.wantsPlayback ? @"playing" : @"paused";
98
+ }
99
+ }
100
+
101
+ - (void)play {
102
+ [self refresh];
103
+ if (!self.player || self.disposed || [self.state isEqual:@"error"]) return;
104
+ if ([self.state isEqual:@"ended"]) {
105
+ [self.player seekToTime:kCMTimeZero];
106
+ self.state = @"paused";
107
+ }
108
+ self.wantsPlayback = YES;
109
+ [self.player play];
110
+ [self refresh];
111
+ }
112
+
113
+ - (void)pause {
114
+ if (!self.player || self.disposed) return;
115
+ self.wantsPlayback = NO;
116
+ [self.player pause];
117
+ [self refresh];
118
+ }
119
+
120
+ - (void)seekSeconds:(double)seconds {
121
+ if (!self.player || self.disposed || !isfinite(seconds)) return;
122
+ if ([self.state isEqual:@"ended"]) self.state = @"paused";
123
+ double duration = CMTimeGetSeconds(self.item.duration);
124
+ seconds = fmax(0, seconds);
125
+ if (isfinite(duration) && duration > 0) seconds = fmin(seconds, duration);
126
+ [self.player seekToTime:CMTimeMakeWithSeconds(seconds, 600) toleranceBefore:kCMTimeZero toleranceAfter:kCMTimeZero];
127
+ }
128
+
129
+ static double safeSeconds(CMTime time) {
130
+ double value = CMTimeGetSeconds(time);
131
+ return isfinite(value) && value > 0 ? value : 0;
132
+ }
133
+
134
+ - (NSString *)snapshot {
135
+ [self refresh];
136
+ NSMutableDictionary *value = [@{
137
+ @"state": self.state,
138
+ @"currentTime": @(self.player ? safeSeconds(self.player.currentTime) : 0),
139
+ @"duration": @(self.item ? safeSeconds(self.item.duration) : 0)
140
+ } mutableCopy];
141
+ if (self.failure) value[@"error"] = self.failure;
142
+ NSData *data = [NSJSONSerialization dataWithJSONObject:value options:0 error:nil];
143
+ return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
144
+ }
145
+
146
+ - (void)clear {
147
+ [self releaseTrack];
148
+ self.failure = nil;
149
+ self.state = @"idle";
150
+ }
151
+
152
+ - (void)dispose {
153
+ if (self.disposed) return;
154
+ self.disposed = YES;
155
+ [self clear];
156
+ }
157
+
158
+ - (void)dealloc {
159
+ [self releaseTrack];
160
+ }
161
+ @end