@windowkit/appkit 0.20.0 → 0.22.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.
package/src/player.mm ADDED
@@ -0,0 +1,424 @@
1
+ // @windowkit/appkit player.mm — a file or URL played by AVFoundation, for a
2
+ // renderer's `<video src>`: the platform's decoder, audio, seeking and HLS,
3
+ // none of it the renderer's.
4
+ //
5
+ // - createPlayer(url, { autoPlay, loop, muted, volume, rate }) -> { id, layer }:
6
+ // an AVPlayer over the URL (a path, a file:// URL or an http(s) one), and
7
+ // the AVPlayerLayer that shows it — a layer handle every layer verb takes,
8
+ // so a renderer places it among its own layers like any other. Its
9
+ // `videoGravity` fills the layer: the renderer fits the picture itself.
10
+ // - playerSet(id, { paused, rate, volume, muted, loop }), playerSeek(id, s).
11
+ // - playerCopyFrame(id, surface) -> { width, height, time } | null: the frame
12
+ // showing now, converted into a 2D surface — for a renderer that draws the
13
+ // video in its own paint order because something is drawn over it — or
14
+ // null when there is no frame newer than the last one copied. Converted in
15
+ // the colours the layer shows the same frame in (video.mm), so a video
16
+ // moving between the two does not change shade.
17
+ // - releasePlayer(id): stopped, and everything it holds let go.
18
+ //
19
+ // Events, by `id`: `player-metadata { width, height, duration }` when the
20
+ // item is ready and whenever its size changes (`duration` is Infinity for a
21
+ // live stream); `player-state { playing, rate }` when it starts or stops;
22
+ // `player-time { currentTime }` four times a second while it plays, and
23
+ // after a seek; `player-ended` at the end of an item that does not loop;
24
+ // `player-error { message }` when the item fails.
25
+ //
26
+ // Everything about a player happens on the UI thread — AVFoundation's KVO and
27
+ // notifications arrive there — and a worker's verbs are commands to it, the
28
+ // layer a handle answered at the call. The one exception is the copy, which
29
+ // reads AVPlayerItemVideoOutput from the calling thread as a display link
30
+ // would, into a surface that thread draws with.
31
+
32
+ #include <napi.h>
33
+ #import <AVFoundation/AVFoundation.h>
34
+ #import <CoreMedia/CoreMedia.h>
35
+ #import <CoreVideo/CoreVideo.h>
36
+ #import <QuartzCore/QuartzCore.h>
37
+
38
+ #include <pthread.h>
39
+
40
+ #include <atomic>
41
+ #include <cmath>
42
+ #include <string>
43
+
44
+ #include "channel.h"
45
+
46
+ // video.mm
47
+ bool CALPixelBufferToBGRA(Napi::Env env, const char* verb, CVPixelBufferRef pb, uint8_t* dst,
48
+ size_t dstStride);
49
+ bool CALVideoTargetBitmap(Napi::Value v, uint8_t** data, size_t* width, size_t* height,
50
+ size_t* bytesPerRow);
51
+
52
+ @interface CALPlayer : NSObject
53
+ @property(nonatomic) double pid;
54
+ @property(nonatomic, strong) AVPlayer* player;
55
+ @property(nonatomic, strong) AVPlayerItem* item;
56
+ @property(nonatomic, strong) AVPlayerLayer* layer;
57
+ // written on the UI thread, read by a copy on any other
58
+ @property(atomic, strong) AVPlayerItemVideoOutput* output;
59
+ @property(nonatomic) BOOL loop;
60
+ @property(nonatomic) float rate;
61
+ @property(nonatomic, strong) id timeObserver;
62
+ @property(nonatomic, strong) NSMutableArray* notes;
63
+ @property(nonatomic) CGSize lastSize;
64
+ @property(nonatomic) double lastDuration;
65
+ @property(nonatomic) BOOL observing;
66
+ @end
67
+
68
+ static void* kStatusContext = &kStatusContext;
69
+ static void* kControlContext = &kControlContext;
70
+ static void* kSizeContext = &kSizeContext;
71
+
72
+ static double Seconds(CMTime t) {
73
+ if (CMTIME_IS_INDEFINITE(t)) return INFINITY;
74
+ double s = CMTimeGetSeconds(t);
75
+ return std::isfinite(s) ? s : 0;
76
+ }
77
+
78
+ @implementation CALPlayer
79
+
80
+ // Once the item is ready, and again whenever its size or its duration
81
+ // moves: before it is ready a size can arrive with the duration still
82
+ // unknown, and a renderer would lay a clip out as a live stream.
83
+ - (void)metadata {
84
+ if (self.item.status != AVPlayerItemStatusReadyToPlay) return;
85
+ CGSize size = self.item.presentationSize;
86
+ if (size.width <= 0 || size.height <= 0) return;
87
+ double duration = Seconds(self.item.duration);
88
+ if (CGSizeEqualToSize(size, self.lastSize) && duration == self.lastDuration) return;
89
+ self.lastSize = size;
90
+ self.lastDuration = duration;
91
+ CALEmit(std::move(CALEvent("player-metadata")
92
+ .Num("id", self.pid)
93
+ .Num("width", size.width)
94
+ .Num("height", size.height)
95
+ .Num("duration", duration)));
96
+ }
97
+
98
+ - (void)observeValueForKeyPath:(NSString*)keyPath
99
+ ofObject:(id)object
100
+ change:(NSDictionary*)change
101
+ context:(void*)context {
102
+ if (context == kStatusContext) {
103
+ if (self.item.status == AVPlayerItemStatusReadyToPlay) {
104
+ [self metadata];
105
+ } else if (self.item.status == AVPlayerItemStatusFailed) {
106
+ NSString* why = self.item.error.localizedDescription ?: @"the item could not be played";
107
+ CALEmit(std::move(CALEvent("player-error").Num("id", self.pid).Str("message", why.UTF8String)));
108
+ }
109
+ } else if (context == kControlContext) {
110
+ BOOL playing = self.player.timeControlStatus != AVPlayerTimeControlStatusPaused;
111
+ CALEmit(std::move(
112
+ CALEvent("player-state").Num("id", self.pid).Bool("playing", playing).Num("rate", self.player.rate)));
113
+ } else if (context == kSizeContext) {
114
+ [self metadata];
115
+ } else {
116
+ [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
117
+ }
118
+ }
119
+
120
+ - (void)start {
121
+ AVPlayerItem* item = self.item;
122
+ [item addObserver:self forKeyPath:@"status" options:0 context:kStatusContext];
123
+ [item addObserver:self forKeyPath:@"presentationSize" options:0 context:kSizeContext];
124
+ [item addObserver:self forKeyPath:@"duration" options:0 context:kSizeContext];
125
+ [self.player addObserver:self forKeyPath:@"timeControlStatus" options:0 context:kControlContext];
126
+ self.observing = YES;
127
+ __weak CALPlayer* weak = self;
128
+ self.timeObserver = [self.player
129
+ addPeriodicTimeObserverForInterval:CMTimeMakeWithSeconds(0.25, 600)
130
+ queue:dispatch_get_main_queue()
131
+ usingBlock:^(CMTime time) {
132
+ CALPlayer* p = weak;
133
+ if (!p) return;
134
+ CALEmit(std::move(CALEvent("player-time")
135
+ .Num("id", p.pid)
136
+ .Num("currentTime", Seconds(time))));
137
+ }];
138
+ NSNotificationCenter* nc = NSNotificationCenter.defaultCenter;
139
+ self.notes = [NSMutableArray array];
140
+ [self.notes addObject:[nc addObserverForName:AVPlayerItemDidPlayToEndTimeNotification
141
+ object:item
142
+ queue:NSOperationQueue.mainQueue
143
+ usingBlock:^(NSNotification* n) {
144
+ CALPlayer* p = weak;
145
+ if (!p) return;
146
+ if (p.loop) {
147
+ [p.player seekToTime:kCMTimeZero
148
+ toleranceBefore:kCMTimeZero
149
+ toleranceAfter:kCMTimeZero];
150
+ [p.player playImmediatelyAtRate:p.rate];
151
+ } else {
152
+ CALEmit(std::move(CALEvent("player-ended").Num("id", p.pid)));
153
+ }
154
+ }]];
155
+ [self.notes addObject:[nc addObserverForName:AVPlayerItemFailedToPlayToEndTimeNotification
156
+ object:item
157
+ queue:NSOperationQueue.mainQueue
158
+ usingBlock:^(NSNotification* n) {
159
+ CALPlayer* p = weak;
160
+ if (!p) return;
161
+ NSError* e = n.userInfo[AVPlayerItemFailedToPlayToEndTimeErrorKey];
162
+ NSString* why = e.localizedDescription ?: @"playback stopped";
163
+ CALEmit(std::move(CALEvent("player-error")
164
+ .Num("id", p.pid)
165
+ .Str("message", why.UTF8String)));
166
+ }]];
167
+ }
168
+
169
+ - (void)stop {
170
+ [self.player pause];
171
+ if (self.observing) {
172
+ [self.item removeObserver:self forKeyPath:@"status" context:kStatusContext];
173
+ [self.item removeObserver:self forKeyPath:@"presentationSize" context:kSizeContext];
174
+ [self.item removeObserver:self forKeyPath:@"duration" context:kSizeContext];
175
+ [self.player removeObserver:self forKeyPath:@"timeControlStatus" context:kControlContext];
176
+ self.observing = NO;
177
+ }
178
+ if (self.timeObserver) [self.player removeTimeObserver:self.timeObserver];
179
+ self.timeObserver = nil;
180
+ for (id note in self.notes) [NSNotificationCenter.defaultCenter removeObserver:note];
181
+ self.notes = nil;
182
+ if (self.output) [self.item removeOutput:self.output];
183
+ self.output = nil;
184
+ [self.player replaceCurrentItemWithPlayerItem:nil];
185
+ self.layer.player = nil;
186
+ }
187
+
188
+ @end
189
+
190
+ // id -> CALPlayer; the UI thread's, but a copy on another thread looks a
191
+ // player's output up, so every access is under the lock
192
+ static NSMutableDictionary<NSNumber*, CALPlayer*>* gPlayers;
193
+ static std::atomic<uint32_t> gNextPlayer{0};
194
+
195
+ static CALPlayer* PlayerFor(double pid) {
196
+ @synchronized([CALPlayer class]) {
197
+ return gPlayers[@(pid)];
198
+ }
199
+ }
200
+
201
+ static NSURL* URLFrom(NSString* s) {
202
+ if ([s rangeOfString:@"://"].location != NSNotFound) return [NSURL URLWithString:s];
203
+ return [NSURL fileURLWithPath:s.stringByExpandingTildeInPath];
204
+ }
205
+
206
+ static bool OptBool(Napi::Object o, const char* k, bool* out) {
207
+ if (!o.Has(k)) return false;
208
+ Napi::Value v = o.Get(k);
209
+ if (!v.IsBoolean()) return false;
210
+ *out = v.As<Napi::Boolean>().Value();
211
+ return true;
212
+ }
213
+
214
+ static bool OptNum(Napi::Object o, const char* k, double* out) {
215
+ if (!o.Has(k)) return false;
216
+ Napi::Value v = o.Get(k);
217
+ if (!v.IsNumber()) return false;
218
+ double d = v.As<Napi::Number>().DoubleValue();
219
+ if (!std::isfinite(d)) return false;
220
+ *out = d;
221
+ return true;
222
+ }
223
+
224
+ // The settings an options object names, read on the calling thread and
225
+ // applied on the UI thread: what is left out stays as it is.
226
+ struct PlayerSettings {
227
+ bool hasPaused = false, paused = false;
228
+ bool hasRate = false;
229
+ double rate = 1;
230
+ bool hasVolume = false;
231
+ double volume = 1;
232
+ bool hasMuted = false, muted = false;
233
+ bool hasLoop = false, loop = false;
234
+ };
235
+
236
+ static PlayerSettings ReadSettings(Napi::Value v) {
237
+ PlayerSettings s;
238
+ if (!v.IsObject()) return s;
239
+ Napi::Object o = v.As<Napi::Object>();
240
+ s.hasPaused = OptBool(o, "paused", &s.paused);
241
+ s.hasRate = OptNum(o, "rate", &s.rate) && s.rate > 0;
242
+ s.hasVolume = OptNum(o, "volume", &s.volume);
243
+ s.hasMuted = OptBool(o, "muted", &s.muted);
244
+ s.hasLoop = OptBool(o, "loop", &s.loop);
245
+ return s;
246
+ }
247
+
248
+ static void Apply(CALPlayer* p, const PlayerSettings& s) {
249
+ if (s.hasLoop) p.loop = s.loop;
250
+ if (s.hasMuted) p.player.muted = s.muted;
251
+ if (s.hasVolume) p.player.volume = (float)fmin(1, fmax(0, s.volume));
252
+ if (s.hasRate) {
253
+ p.rate = (float)s.rate;
254
+ if (p.player.rate != 0) p.player.rate = p.rate;
255
+ }
256
+ if (s.hasPaused) {
257
+ if (s.paused) [p.player pause];
258
+ else [p.player playImmediatelyAtRate:p.rate];
259
+ }
260
+ }
261
+
262
+ static Napi::Value CreatePlayer(const Napi::CallbackInfo& info) {
263
+ Napi::Env env = info.Env();
264
+ if (!info[0].IsString() || info[0].As<Napi::String>().Utf8Value().empty()) {
265
+ Napi::TypeError::New(env, "createPlayer(url, options): url is a path or a URL string")
266
+ .ThrowAsJavaScriptException();
267
+ return env.Undefined();
268
+ }
269
+ NSString* url = [NSString stringWithUTF8String:info[0].As<Napi::String>().Utf8Value().c_str()];
270
+ NSURL* u = URLFrom(url);
271
+ if (!u) {
272
+ Napi::TypeError::New(env, "createPlayer: " + info[0].As<Napi::String>().Utf8Value() +
273
+ " is not a URL AVFoundation can open")
274
+ .ThrowAsJavaScriptException();
275
+ return env.Undefined();
276
+ }
277
+ PlayerSettings settings = ReadSettings(info.Length() > 1 ? info[1] : env.Undefined());
278
+ bool autoPlay = false;
279
+ if (info.Length() > 1 && info[1].IsObject()) OptBool(info[1].As<Napi::Object>(), "autoPlay", &autoPlay);
280
+ double pid = (double)(++gNextPlayer);
281
+
282
+ CALPlayer* (^make)(void) = ^CALPlayer* {
283
+ CALPlayer* p = [CALPlayer new];
284
+ p.pid = pid;
285
+ p.rate = 1;
286
+ p.item = [AVPlayerItem playerItemWithURL:u];
287
+ p.player = [AVPlayer playerWithPlayerItem:p.item];
288
+ // the end is the renderer's to answer — loop, or say it ended
289
+ p.player.actionAtItemEnd = AVPlayerActionAtItemEndPause;
290
+ p.layer = [AVPlayerLayer playerLayerWithPlayer:p.player];
291
+ p.layer.videoGravity = AVLayerVideoGravityResize;
292
+ // YCbCr out, in the layout VideoToolbox decodes to: a copy for the drawn
293
+ // presentation is then converted here, in the layer's colours
294
+ p.output = [[AVPlayerItemVideoOutput alloc] initWithPixelBufferAttributes:@{
295
+ (id)kCVPixelBufferPixelFormatTypeKey : @[
296
+ @(kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange),
297
+ @(kCVPixelFormatType_420YpCbCr8BiPlanarFullRange)
298
+ ],
299
+ (id)kCVPixelBufferIOSurfacePropertiesKey : @{},
300
+ }];
301
+ [p.item addOutput:p.output];
302
+ Apply(p, settings);
303
+ [p start];
304
+ if (autoPlay) [p.player playImmediatelyAtRate:p.rate];
305
+ @synchronized([CALPlayer class]) {
306
+ if (!gPlayers) gPlayers = [NSMutableDictionary dictionary];
307
+ gPlayers[@(pid)] = p;
308
+ }
309
+ return p;
310
+ };
311
+
312
+ Napi::Object out = Napi::Object::New(env);
313
+ out.Set("id", pid);
314
+ if (pthread_main_np()) {
315
+ CALPlayer* p = make();
316
+ void* retained = (void*)CFBridgingRetain(p.layer);
317
+ out.Set("layer", Napi::External<void>::New(env, retained, [](Napi::Env, void* d) { CFRelease(d); }));
318
+ } else {
319
+ CALHandle* h = CALNewHandle();
320
+ out.Set("layer", CALWrapHandle(env, h, false));
321
+ CALOnUI(^{ h->object_ = make().layer; });
322
+ }
323
+ return out;
324
+ }
325
+
326
+ static Napi::Value PlayerSet(const Napi::CallbackInfo& info) {
327
+ Napi::Env env = info.Env();
328
+ if (!info[0].IsNumber()) {
329
+ Napi::TypeError::New(env, "playerSet(id, settings): id is the number createPlayer answered")
330
+ .ThrowAsJavaScriptException();
331
+ return env.Undefined();
332
+ }
333
+ double pid = info[0].As<Napi::Number>().DoubleValue();
334
+ PlayerSettings settings = ReadSettings(info.Length() > 1 ? info[1] : env.Undefined());
335
+ CALOnUI(^{
336
+ CALPlayer* p = PlayerFor(pid);
337
+ if (p) Apply(p, settings);
338
+ });
339
+ return env.Undefined();
340
+ }
341
+
342
+ static Napi::Value PlayerSeek(const Napi::CallbackInfo& info) {
343
+ Napi::Env env = info.Env();
344
+ if (!info[0].IsNumber() || !info[1].IsNumber()) {
345
+ Napi::TypeError::New(env, "playerSeek(id, seconds): two numbers").ThrowAsJavaScriptException();
346
+ return env.Undefined();
347
+ }
348
+ double pid = info[0].As<Napi::Number>().DoubleValue();
349
+ double seconds = fmax(0, info[1].As<Napi::Number>().DoubleValue());
350
+ CALOnUI(^{
351
+ CALPlayer* p = PlayerFor(pid);
352
+ if (!p) return;
353
+ __weak CALPlayer* weak = p;
354
+ [p.player seekToTime:CMTimeMakeWithSeconds(seconds, 600)
355
+ toleranceBefore:kCMTimeZero
356
+ toleranceAfter:kCMTimeZero
357
+ completionHandler:^(BOOL finished) {
358
+ CALPlayer* q = weak;
359
+ if (!q || !finished) return;
360
+ // the time the seek landed on, at once: a paused player's periodic
361
+ // observer would otherwise say nothing until it plays
362
+ CALEmit(std::move(CALEvent("player-time")
363
+ .Num("id", q.pid)
364
+ .Num("currentTime", Seconds(q.player.currentTime))));
365
+ }];
366
+ });
367
+ return env.Undefined();
368
+ }
369
+
370
+ static Napi::Value PlayerCopyFrame(const Napi::CallbackInfo& info) {
371
+ Napi::Env env = info.Env();
372
+ if (!info[0].IsNumber()) {
373
+ Napi::TypeError::New(env, "playerCopyFrame(id, surface): id is the number createPlayer answered")
374
+ .ThrowAsJavaScriptException();
375
+ return env.Undefined();
376
+ }
377
+ uint8_t* data;
378
+ size_t sw, sh, bpr;
379
+ if (!CALVideoTargetBitmap(info[1], &data, &sw, &sh, &bpr)) return env.Undefined();
380
+ CALPlayer* p = PlayerFor(info[0].As<Napi::Number>().DoubleValue());
381
+ AVPlayerItemVideoOutput* output = p.output;
382
+ if (!output) return env.Null();
383
+ CMTime t = [output itemTimeForHostTime:CACurrentMediaTime()];
384
+ if (![output hasNewPixelBufferForItemTime:t]) return env.Null();
385
+ CMTime shown = kCMTimeInvalid;
386
+ CVPixelBufferRef pb = [output copyPixelBufferForItemTime:t itemTimeForDisplay:&shown];
387
+ if (!pb) return env.Null();
388
+ size_t w = CVPixelBufferGetWidth(pb), h = CVPixelBufferGetHeight(pb);
389
+ Napi::Object out = Napi::Object::New(env);
390
+ out.Set("width", (double)w);
391
+ out.Set("height", (double)h);
392
+ out.Set("time", Seconds(CMTIME_IS_VALID(shown) ? shown : t));
393
+ // a surface of another size than the frame is the renderer's to remake:
394
+ // it is told the size, and nothing is written
395
+ bool fits = w == sw && h == sh;
396
+ bool ok = !fits || CALPixelBufferToBGRA(env, "playerCopyFrame", pb, data, bpr);
397
+ CVPixelBufferRelease(pb);
398
+ if (!ok) return env.Undefined();
399
+ out.Set("written", fits);
400
+ return out;
401
+ }
402
+
403
+ static Napi::Value ReleasePlayer(const Napi::CallbackInfo& info) {
404
+ Napi::Env env = info.Env();
405
+ if (!info[0].IsNumber()) return env.Undefined();
406
+ double pid = info[0].As<Napi::Number>().DoubleValue();
407
+ CALOnUI(^{
408
+ CALPlayer* p;
409
+ @synchronized([CALPlayer class]) {
410
+ p = gPlayers[@(pid)];
411
+ [gPlayers removeObjectForKey:@(pid)];
412
+ }
413
+ [p stop];
414
+ });
415
+ return env.Undefined();
416
+ }
417
+
418
+ void InitPlayer(Napi::Env env, Napi::Object exports) {
419
+ exports.Set("createPlayer", Napi::Function::New(env, CreatePlayer));
420
+ exports.Set("playerSet", Napi::Function::New(env, PlayerSet));
421
+ exports.Set("playerSeek", Napi::Function::New(env, PlayerSeek));
422
+ exports.Set("playerCopyFrame", Napi::Function::New(env, PlayerCopyFrame));
423
+ exports.Set("releasePlayer", Napi::Function::New(env, ReleasePlayer));
424
+ }