@windowkit/appkit 0.21.0 → 0.23.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/README.md CHANGED
@@ -558,6 +558,24 @@ native.ctxSetGlobalAlpha(win, 0.6);
558
558
  native.ctxDrawSurfaceFaded(win, card, 0, 0, 556, 300, 100, 100, 556, 300, 0.6);
559
559
  ```
560
560
 
561
+ - **`native.ctxSetImageSmoothing(surface, quality)`** — how an image or a surface drawn
562
+ scaled or turned is resampled: `'none'` (the nearest pixel), `'low'`, `'medium'` or
563
+ `'high'`, the 2D canvas's `imageSmoothingEnabled` and `imageSmoothingQuality`. It is
564
+ part of the graphics state, so `ctxSave` and `ctxRestore` scope it, and every context
565
+ starts at `'medium'`. At `'medium'` CoreGraphics resamples the whole source image for a
566
+ draw through a matrix, whatever the clip, so a surface drawn a tile at a time — a box
567
+ in perspective, each tile under its own clip and the matrix of the plane over it —
568
+ costs each tile all of the surface: 784 tiles of a 1400x1120 surface take some 200ms
569
+ on an M1 Pro, and 27ms at `'low'`, which is bilinear, what a layer in perspective is
570
+ drawn with. A draw at 1:1 on whole pixels is the same at every quality.
571
+
572
+ ```js
573
+ native.ctxSave(win);
574
+ native.ctxSetImageSmoothing(win, 'low');
575
+ // …the tiles…
576
+ native.ctxRestore(win);
577
+ ```
578
+
561
579
  ## Video surfaces
562
580
 
563
581
  A frame a decoder hands over as bytes — ffmpeg over a pipe, a WASM decoder, an addon —
@@ -607,6 +625,39 @@ Two things the verbs exist to get right, both measured on screen (`test/video-su
607
625
  agree to within a level or two. What cannot match is gamut: a layer keeps a 2020
608
626
  colour outside sRGB on a wide-gamut panel, and an sRGB bitmap clips it.
609
627
 
628
+ ## Playing a file
629
+
630
+ A file or URL played by AVFoundation — the platform's decoder, audio, seeking and HLS —
631
+ for a renderer's `<video src>`, with the picture on a layer the renderer places among its
632
+ own, and the frame showing drawable into a surface when something is drawn over it.
633
+
634
+ - **`native.createPlayer(url, { autoPlay, loop, muted, volume, rate })`** →
635
+ `{ id, layer }`. `url` is a path, a `file://` URL or an `http(s)` one. `layer` is the
636
+ `AVPlayerLayer` that shows it, a handle every layer verb takes (`addSublayer`,
637
+ `setLayerProps`, `removeFromSuperlayer`); its `videoGravity` fills the layer, so the
638
+ renderer fits the picture itself. Nothing plays until `autoPlay` or `paused: false`.
639
+ - **`native.playerSet(id, { paused, rate, volume, muted, loop })`** — what it names
640
+ changes, the rest stays; **`native.playerSeek(id, seconds)`** — exact, not to the
641
+ nearest keyframe.
642
+ - **`native.playerCopyFrame(id, surface)`** → `{ width, height, time, written }`, or
643
+ `null` when no frame is newer than the last one copied: the frame showing now,
644
+ converted into a 2D surface of the frame's size in the colours the layer shows it in
645
+ (the same conversion as `writeVideoSurface`). A surface of another size is told the
646
+ size and left alone (`written: false`). It reads `AVPlayerItemVideoOutput` on the
647
+ calling thread, as a display link would, so a worker's renderer copies without a hop.
648
+ - **`native.releasePlayer(id)`** — stopped, and everything it holds let go; its events
649
+ stop.
650
+
651
+ Its events go through `setBackendEventCallback`, by `id`: `player-metadata { width,
652
+ height, duration }` once the item is ready, and again if either moves (`duration` is
653
+ `Infinity` for a live stream); `player-state { playing, rate }` when it starts or stops;
654
+ `player-time { currentTime }` four times a second while it plays and once after a seek;
655
+ `player-ended` at the end of an item that does not loop; `player-error { message }`.
656
+
657
+ `test/player.js` plays `test/fixtures/clip.mp4` — 1.5s of one colour, 160x90 H.264
658
+ tagged BT.709 — on a layer and copied into a surface beside it, and holds the two to
659
+ the same colour on screen: 211, 127, 67 and 211, 127, 68 on an M1 Pro.
660
+
610
661
  ## Text: at a display's scale
611
662
 
612
663
  A text verb's size is the caller's pixels, and a renderer that draws in device pixels hands
package/binding.gyp CHANGED
@@ -10,7 +10,8 @@
10
10
  "src/calendars.mm",
11
11
  "src/screencolor.mm",
12
12
  "src/threaded.mm",
13
- "src/video.mm"
13
+ "src/video.mm",
14
+ "src/player.mm"
14
15
  ],
15
16
  "include_dirs": [
16
17
  "<!@(node -p \"require('node-addon-api').include\")"
@@ -31,6 +32,7 @@
31
32
  "-framework IOSurface",
32
33
  "-framework CoreVideo",
33
34
  "-framework VideoToolbox",
35
+ "-framework CoreMedia",
34
36
  "-framework UniformTypeIdentifiers",
35
37
  "-framework AVFoundation",
36
38
  "-framework CoreLocation",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@windowkit/appkit",
3
- "version": "0.21.0",
3
+ "version": "0.23.0",
4
4
  "description": "Retained-mode AppKit backend for Node.js: Core Animation (CALayer) layer trees, CoreText layout and drawing, IOSurface presentation, NSMenu, and native control bezels — the macOS half of react-x11.",
5
5
  "author": "Andrey Sidorov <andrey.sidorov@gmail.com>",
6
6
  "license": "MIT",
@@ -43,7 +43,7 @@
43
43
  "install": "node scripts/install.js",
44
44
  "build": "node-gyp rebuild",
45
45
  "demo": "node demo/demo.js",
46
- "test": "node test/app-lifecycle.js && node test/animation.js && node test/layer-transform.js && node test/accessibility-display.js && node test/ignores-mouse-events.js && node test/popup-menu.js && node test/surface-blit.js && node test/surface-faded.js && node test/surface-colorspace.js && node test/video-surface.js && node test/round-rect-xy.js && node test/control-bezels.js && node test/text-features.js && node test/font-from-data.js && node test/text-coverage.js && node test/text-typesetter.js && node test/text-line-height.js && node test/text-line-width.js && node test/text-scale.js && node test/symbols.js && node test/eventkit-permissions.js && node test/calendars.js && node test/calendar-writes.js && node test/screencolor.js && node test/notifications.js && node test/threaded.js && node test/threaded-verbs.js && node test/threaded-frames.js && node test/threaded-resize.js && node test/ending-worker.js && node test/live-resize.js && node test/activation-policy.js"
46
+ "test": "node test/app-lifecycle.js && node test/animation.js && node test/layer-transform.js && node test/accessibility-display.js && node test/ignores-mouse-events.js && node test/popup-menu.js && node test/surface-blit.js && node test/surface-faded.js && node test/image-smoothing.js && node test/surface-colorspace.js && node test/video-surface.js && node test/player.js && node test/round-rect-xy.js && node test/clip-rule.js && node test/control-bezels.js && node test/text-features.js && node test/font-from-data.js && node test/text-coverage.js && node test/text-typesetter.js && node test/text-line-height.js && node test/text-line-width.js && node test/text-scale.js && node test/symbols.js && node test/eventkit-permissions.js && node test/calendars.js && node test/calendar-writes.js && node test/screencolor.js && node test/notifications.js && node test/threaded.js && node test/threaded-verbs.js && node test/threaded-frames.js && node test/threaded-resize.js && node test/ending-worker.js && node test/live-resize.js && node test/activation-policy.js"
47
47
  },
48
48
  "dependencies": {
49
49
  "node-addon-api": "^8.3.0"
Binary file
package/src/addon.mm CHANGED
@@ -1721,6 +1721,9 @@ void InitThreaded(Napi::Env env, Napi::Object exports);
1721
1721
  // src/video.mm — video surfaces: a YCbCr or BGRA IOSurface a layer shows
1722
1722
  // as it is, frames written into it, and frames converted into a surface.
1723
1723
  void InitVideo(Napi::Env env, Napi::Object exports);
1724
+ // src/player.mm — a file or URL played by AVFoundation: an AVPlayer, its
1725
+ // AVPlayerLayer as a layer handle, and the frame showing copied into a surface.
1726
+ void InitPlayer(Napi::Env env, Napi::Object exports);
1724
1727
 
1725
1728
  static Napi::Object Init(Napi::Env env, Napi::Object exports) {
1726
1729
  #define FN(js, fn) exports.Set(js, Napi::Function::New(env, fn))
@@ -1768,6 +1771,7 @@ static Napi::Object Init(Napi::Env env, Napi::Object exports) {
1768
1771
  InitScreenColor(env, exports);
1769
1772
  InitThreaded(env, exports);
1770
1773
  InitVideo(env, exports);
1774
+ InitPlayer(env, exports);
1771
1775
  return exports;
1772
1776
  }
1773
1777
 
package/src/backend.mm CHANGED
@@ -4192,6 +4192,24 @@ static Napi::Value CtxSetGlobalAlpha(const Napi::CallbackInfo& info) {
4192
4192
  info[1].As<Napi::Number>().DoubleValue());
4193
4193
  return info.Env().Undefined();
4194
4194
  }
4195
+ // ctxSetImageSmoothing(surface, quality) — how an image drawn scaled or
4196
+ // turned is resampled: 'none' (the nearest pixel), 'low', 'medium' or
4197
+ // 'high', the 2D canvas's imageSmoothingEnabled and imageSmoothingQuality.
4198
+ // Part of the graphics state, so ctxSave/ctxRestore scope it. Every
4199
+ // context this bridge makes starts at 'medium', which resamples the whole
4200
+ // source image for a draw through a matrix whatever the clip: 784 tiles of
4201
+ // a 1400x1120 surface, each drawn under its own clip and matrix, took 214ms
4202
+ // on an M1 Pro, and 29.6ms at 'low', which is bilinear — what a layer in
4203
+ // perspective is drawn with.
4204
+ static Napi::Value CtxSetImageSmoothing(const Napi::CallbackInfo& info) {
4205
+ std::string q = info[1].As<Napi::String>().Utf8Value();
4206
+ CGContextSetInterpolationQuality(CtxOf(info[0]),
4207
+ q == "none" ? kCGInterpolationNone
4208
+ : q == "low" ? kCGInterpolationLow
4209
+ : q == "high" ? kCGInterpolationHigh
4210
+ : kCGInterpolationMedium);
4211
+ return info.Env().Undefined();
4212
+ }
4195
4213
  static Napi::Value CtxSetLineCap(const Napi::CallbackInfo& info) {
4196
4214
  std::string cap = info[1].As<Napi::String>().Utf8Value();
4197
4215
  CGContextSetLineCap(CtxOf(info[0]),
@@ -4299,10 +4317,17 @@ static Napi::Value CtxStroke(const Napi::CallbackInfo& info) {
4299
4317
  KeepPathAround(s->ctx, ^{ CGContextStrokePath(s->ctx); });
4300
4318
  return info.Env().Undefined();
4301
4319
  }
4320
+ // ctxClip(surface, evenOdd): the flag ctxFill takes, so canvas's
4321
+ // clip(path, 'evenodd') — an SVG <clipPath> with clip-rule="evenodd" — cuts
4322
+ // a ring rather than the square around it. Absent is nonzero, as before.
4302
4323
  static Napi::Value CtxClip(const Napi::CallbackInfo& info) {
4303
4324
  CALSurface* s = SurfaceFrom(info[0]);
4304
4325
  if (!s) return info.Env().Undefined();
4305
- KeepPathAround(s->ctx, ^{ CGContextClip(s->ctx); });
4326
+ bool evenOdd = info.Length() > 1 && info[1].ToBoolean().Value();
4327
+ KeepPathAround(s->ctx, ^{
4328
+ if (evenOdd) CGContextEOClip(s->ctx);
4329
+ else CGContextClip(s->ctx);
4330
+ });
4306
4331
  return info.Env().Undefined();
4307
4332
  }
4308
4333
 
@@ -7786,6 +7811,7 @@ void InitBackend(Napi::Env env, Napi::Object exports) {
7786
7811
  BFN("ctxSetStrokeColor", CtxSetStrokeColor);
7787
7812
  BFN("ctxSetLineWidth", CtxSetLineWidth);
7788
7813
  BFN("ctxSetGlobalAlpha", CtxSetGlobalAlpha);
7814
+ BFN("ctxSetImageSmoothing", CtxSetImageSmoothing);
7789
7815
  BFN("ctxSetLineCap", CtxSetLineCap);
7790
7816
  BFN("ctxSetLineJoin", CtxSetLineJoin);
7791
7817
  BFN("ctxSetBlendMode", CtxSetBlendMode);
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
+ }
package/src/video.mm CHANGED
@@ -700,6 +700,100 @@ bool CALNameVideoColorSpace(IOSurfaceRef ios) {
700
700
  return true;
701
701
  }
702
702
 
703
+ // A decoded frame — a player's, from AVPlayerItemVideoOutput (player.mm) —
704
+ // into BGRA rows at `dst`, opaque, in sRGB: read in the colour its own
705
+ // attachments name, which is what Core Animation shows the same buffer in on
706
+ // a layer. YCbCr goes through the routes above; BGRA is copied. False, with
707
+ // an error pending, for a layout neither takes. The caller holds no lock.
708
+ bool CALPixelBufferToBGRA(Napi::Env env, const char* verb, CVPixelBufferRef pb, uint8_t* dst,
709
+ size_t dstStride) {
710
+ OSType type = CVPixelBufferGetPixelFormatType(pb);
711
+ size_t w = CVPixelBufferGetWidth(pb), h = CVPixelBufferGetHeight(pb);
712
+ Format format;
713
+ Colour colour;
714
+ switch (type) {
715
+ case kCVPixelFormatType_420YpCbCr8BiPlanarFullRange:
716
+ colour.full = true;
717
+ [[fallthrough]];
718
+ case kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange:
719
+ format = Format::NV12;
720
+ break;
721
+ case kCVPixelFormatType_420YpCbCr8PlanarFullRange:
722
+ colour.full = true;
723
+ [[fallthrough]];
724
+ case kCVPixelFormatType_420YpCbCr8Planar:
725
+ format = Format::I420;
726
+ break;
727
+ case kCVPixelFormatType_32BGRA:
728
+ format = Format::BGRA;
729
+ break;
730
+ default:
731
+ Napi::Error::New(env, std::string(verb) + ": a frame in a layout this bridge does not read")
732
+ .ThrowAsJavaScriptException();
733
+ return false;
734
+ }
735
+ #pragma clang diagnostic push
736
+ #pragma clang diagnostic ignored "-Wdeprecated-declarations"
737
+ CFTypeRef m = CVBufferGetAttachment(pb, kCVImageBufferYCbCrMatrixKey, nullptr);
738
+ CFTypeRef p = CVBufferGetAttachment(pb, kCVImageBufferColorPrimariesKey, nullptr);
739
+ CFTypeRef t = CVBufferGetAttachment(pb, kCVImageBufferTransferFunctionKey, nullptr);
740
+ #pragma clang diagnostic pop
741
+ // what a decoder said its frame is; untagged, it is taken to be 709, which
742
+ // is what an untagged HD stream is
743
+ for (CFStringRef known : {kCVImageBufferYCbCrMatrix_ITU_R_709_2,
744
+ kCVImageBufferYCbCrMatrix_ITU_R_601_4,
745
+ kCVImageBufferYCbCrMatrix_ITU_R_2020}) {
746
+ if (m && CFEqual(m, known)) colour.matrix = known;
747
+ }
748
+ for (CFStringRef known : {kCVImageBufferColorPrimaries_ITU_R_709_2,
749
+ kCVImageBufferColorPrimaries_SMPTE_C,
750
+ kCVImageBufferColorPrimaries_EBU_3213,
751
+ kCVImageBufferColorPrimaries_ITU_R_2020}) {
752
+ if (p && CFEqual(p, known)) colour.primaries = known;
753
+ }
754
+ for (CFStringRef known : {kCVImageBufferTransferFunction_ITU_R_709_2,
755
+ kCVImageBufferTransferFunction_ITU_R_2020,
756
+ kCVImageBufferTransferFunction_sRGB}) {
757
+ if (t && CFEqual(t, known)) colour.transfer = known;
758
+ }
759
+ CVPixelBufferLockBaseAddress(pb, kCVPixelBufferLock_ReadOnly);
760
+ std::vector<Plane> planes;
761
+ if (format == Format::BGRA) {
762
+ planes.push_back({(const uint8_t*)CVPixelBufferGetBaseAddress(pb), 0,
763
+ CVPixelBufferGetBytesPerRow(pb), w * 4, h});
764
+ } else {
765
+ size_t n = CVPixelBufferGetPlaneCount(pb);
766
+ for (size_t i = 0; i < n; i++) {
767
+ size_t pw = CVPixelBufferGetWidthOfPlane(pb, i);
768
+ planes.push_back({(const uint8_t*)CVPixelBufferGetBaseAddressOfPlane(pb, i), 0,
769
+ CVPixelBufferGetBytesPerRowOfPlane(pb, i),
770
+ format == Format::NV12 && i == 1 ? pw * 2 : pw,
771
+ CVPixelBufferGetHeightOfPlane(pb, i)});
772
+ }
773
+ }
774
+ bool ok;
775
+ if (format == Format::BGRA) {
776
+ CopyOpaqueRows(dst, dstStride, planes[0], w);
777
+ ok = true;
778
+ } else {
779
+ ok = ConvertToBGRA(env, verb, format, planes, w, h, colour, dst, dstStride);
780
+ }
781
+ CVPixelBufferUnlockBaseAddress(pb, kCVPixelBufferLock_ReadOnly);
782
+ return ok;
783
+ }
784
+
785
+ // A 2D surface's bitmap, for player.mm, which writes into one too.
786
+ bool CALVideoTargetBitmap(Napi::Value v, uint8_t** data, size_t* width, size_t* height,
787
+ size_t* bytesPerRow) {
788
+ CALSurfaceBits bits;
789
+ if (!CALSurfaceBitmap(v, &bits)) return false;
790
+ *data = bits.data;
791
+ *width = bits.width;
792
+ *height = bits.height;
793
+ *bytesPerRow = bits.bytesPerRow;
794
+ return true;
795
+ }
796
+
703
797
  void InitVideo(Napi::Env env, Napi::Object exports) {
704
798
  exports.Set("createVideoSurface", Napi::Function::New(env, CreateVideoSurface));
705
799
  exports.Set("writeVideoSurface", Napi::Function::New(env, WriteVideoSurface));