@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/video.mm ADDED
@@ -0,0 +1,803 @@
1
+ // @windowkit/appkit video.mm — video frames a renderer is handed as bytes,
2
+ // shown on a layer as they are or drawn into a surface.
3
+ //
4
+ // A decoder that is not the platform's — ffmpeg over a pipe, a WASM module,
5
+ // an addon — hands a renderer planes of bytes, and the cheapest way to put
6
+ // them on the screen is the way VideoToolbox's own output gets there: a
7
+ // YCbCr IOSurface as a plain layer's contents. The render server converts
8
+ // and scales it, in the GPU, on its own clock; the CPU's share is the copy
9
+ // in and a transaction. Measured for react-x11's video design record
10
+ // (docs/architecture/video.md §3.4): `420v`, `420f` and `2vuy` surfaces all
11
+ // show on screen — through the window server, not through
12
+ // CALayer.render(in:), which draws none of them — and the three-plane
13
+ // layouts (`y420`, `f420`) draw nothing. So:
14
+ //
15
+ // - createVideoSurface(width, height, { format, colorSpace, range })
16
+ // -> { handle, iosurfaceId }: an IOSurface-backed CVPixelBuffer, `NV12`
17
+ // (two planes, `420v` or `420f` by range) or `BGRA`, carrying the colour
18
+ // attachments CoreVideo gives a decoded frame — matrix, primaries and
19
+ // transfer function, which CoreVideo mirrors onto the IOSurface where Core
20
+ // Animation reads them. Shown through setLayerContentsIOSurface by id,
21
+ // like any other IOSurface; that verb keeps the colour the surface names.
22
+ // - writeVideoSurface(target, format, planes, options?): one frame in.
23
+ // `NV12` and `I420` into an NV12 surface — I420's two chroma planes
24
+ // interleaved on the way, the copy the write makes anyway — and `BGRA`
25
+ // into a BGRA one. Into a BGRA surface, or into a 2D surface
26
+ // (createSurface, createSurfaceIOSurface) for a renderer that draws the
27
+ // frame in its own paint order, a YCbCr frame is converted by
28
+ // VideoToolbox's pixel transfer, colour-matched to sRGB, so that the
29
+ // frame drawn into a bitmap and the same frame on a layer show the same
30
+ // colours.
31
+ // - videoSurfaceIsInUse(handle), releaseVideoSurface(handle) — the
32
+ // surface verbs' counterparts, so a renderer keeping a ring of them writes
33
+ // only into one the render server has let go.
34
+ // - videoFormats() -> { surfaces, frames }: what this bridge makes and
35
+ // takes, for a renderer to ask rather than assume.
36
+ //
37
+ // Every verb runs on the calling thread — a worker's, in threaded mode —
38
+ // and none touches a layer: the copy is IOSurface memory under its own
39
+ // lock, and the flip is setLayerContentsIOSurface's, which goes through the
40
+ // layer queue like every other layer change.
41
+
42
+ #include <napi.h>
43
+ #import <CoreVideo/CoreVideo.h>
44
+ #import <Foundation/Foundation.h>
45
+ #import <IOSurface/IOSurface.h>
46
+ #import <VideoToolbox/VideoToolbox.h>
47
+
48
+ #include <cmath>
49
+
50
+ #include <cstdint>
51
+ #include <cstring>
52
+ #include <string>
53
+ #include <vector>
54
+
55
+ // A 2D surface's bitmap (backend.mm): false, with a JS error pending, when
56
+ // `v` is not a live surface handle.
57
+ struct CALSurfaceBits {
58
+ uint8_t* data;
59
+ size_t width, height, bytesPerRow;
60
+ };
61
+ bool CALSurfaceBitmap(Napi::Value v, CALSurfaceBits* out);
62
+ // Name an IOSurface's colour space sRGB (backend.mm).
63
+ void CALNameSurfaceSRGB(IOSurfaceRef ios, bool keep);
64
+ // Name an IOSurface's colour space from its video tags (below).
65
+ bool CALNameVideoColorSpace(IOSurfaceRef ios);
66
+
67
+ namespace {
68
+
69
+ // What tells a video surface's handle from a 2D surface's: both are
70
+ // Externals, and writeVideoSurface takes either.
71
+ const napi_type_tag kVideoSurfaceTag = {0x8c1e5b2d7a4f4e19ULL,
72
+ 0xb36d0f2a91c84e57ULL};
73
+
74
+ const size_t kMaxSide = 16384;
75
+
76
+ enum class Format { NV12, I420, BGRA };
77
+
78
+ const char* FormatName(Format f) {
79
+ switch (f) {
80
+ case Format::NV12:
81
+ return "NV12";
82
+ case Format::I420:
83
+ return "I420";
84
+ case Format::BGRA:
85
+ return "BGRA";
86
+ }
87
+ return "?";
88
+ }
89
+
90
+ bool ParseFormat(Napi::Value v, Format* out) {
91
+ if (!v.IsString()) return false;
92
+ std::string s = v.As<Napi::String>().Utf8Value();
93
+ if (s == "NV12") *out = Format::NV12;
94
+ else if (s == "I420") *out = Format::I420;
95
+ else if (s == "BGRA") *out = Format::BGRA;
96
+ else return false;
97
+ return true;
98
+ }
99
+
100
+ // What a frame's numbers mean: the attachments CoreVideo puts on a decoded
101
+ // buffer, which Core Animation and VideoToolbox both read.
102
+ struct Colour {
103
+ CFStringRef matrix = kCVImageBufferYCbCrMatrix_ITU_R_709_2;
104
+ CFStringRef primaries = kCVImageBufferColorPrimaries_ITU_R_709_2;
105
+ CFStringRef transfer = kCVImageBufferTransferFunction_ITU_R_709_2;
106
+ bool full = false;
107
+ };
108
+
109
+ // `colorSpace` ('bt709' by default, 'bt601', 'bt2020') and `range`
110
+ // ('video' by default, 'full') off an options object. False, with a
111
+ // TypeError pending, for a value that is not one of those.
112
+ bool ParseColour(Napi::Env env, const char* verb, Napi::Object o, Colour* c) {
113
+ if (o.Has("colorSpace") && !o.Get("colorSpace").IsUndefined()) {
114
+ Napi::Value v = o.Get("colorSpace");
115
+ std::string s = v.IsString() ? v.As<Napi::String>().Utf8Value() : "";
116
+ if (s == "bt709") {
117
+ // the defaults
118
+ } else if (s == "bt601") {
119
+ // SD: the 601 matrix with SMPTE C primaries (SMPTE 170M), which is
120
+ // what an untagged SD stream is taken to be
121
+ c->matrix = kCVImageBufferYCbCrMatrix_ITU_R_601_4;
122
+ c->primaries = kCVImageBufferColorPrimaries_SMPTE_C;
123
+ } else if (s == "bt2020") {
124
+ // SDR only: the 2020 matrix and primaries, the 709 curve (which is
125
+ // what 2020's SDR transfer is)
126
+ c->matrix = kCVImageBufferYCbCrMatrix_ITU_R_2020;
127
+ c->primaries = kCVImageBufferColorPrimaries_ITU_R_2020;
128
+ } else {
129
+ Napi::TypeError::New(env, std::string(verb) +
130
+ ": colorSpace must be 'bt709', 'bt601' "
131
+ "or 'bt2020'")
132
+ .ThrowAsJavaScriptException();
133
+ return false;
134
+ }
135
+ }
136
+ if (o.Has("range") && !o.Get("range").IsUndefined()) {
137
+ Napi::Value v = o.Get("range");
138
+ std::string s = v.IsString() ? v.As<Napi::String>().Utf8Value() : "";
139
+ if (s == "full") {
140
+ c->full = true;
141
+ } else if (s != "video") {
142
+ Napi::TypeError::New(env, std::string(verb) +
143
+ ": range must be 'video' or 'full'")
144
+ .ThrowAsJavaScriptException();
145
+ return false;
146
+ }
147
+ }
148
+ return true;
149
+ }
150
+
151
+ void Attach(CVPixelBufferRef pb, const Colour& c) {
152
+ CVBufferSetAttachment(pb, kCVImageBufferYCbCrMatrixKey, c.matrix,
153
+ kCVAttachmentMode_ShouldPropagate);
154
+ CVBufferSetAttachment(pb, kCVImageBufferColorPrimariesKey, c.primaries,
155
+ kCVAttachmentMode_ShouldPropagate);
156
+ CVBufferSetAttachment(pb, kCVImageBufferTransferFunctionKey, c.transfer,
157
+ kCVAttachmentMode_ShouldPropagate);
158
+ }
159
+
160
+ // sRGB, as attachments: what every bitmap this bridge draws into is, and so
161
+ // what a converted frame is matched to.
162
+ void AttachSRGB(CVPixelBufferRef pb) {
163
+ CVBufferSetAttachment(pb, kCVImageBufferColorPrimariesKey,
164
+ kCVImageBufferColorPrimaries_ITU_R_709_2,
165
+ kCVAttachmentMode_ShouldPropagate);
166
+ CVBufferSetAttachment(pb, kCVImageBufferTransferFunctionKey,
167
+ kCVImageBufferTransferFunction_sRGB,
168
+ kCVAttachmentMode_ShouldPropagate);
169
+ }
170
+
171
+ // The IOSurface alone, not the CVPixelBuffer it was made through: a pixel
172
+ // buffer holds a use count on its surface for as long as it lives, so
173
+ // IOSurfaceIsInUse would answer true for a surface nothing shows, and a
174
+ // renderer could never tell which of its ring the render server let go.
175
+ // The attachments are the surface's own values by then, and a pixel buffer
176
+ // is wrapped around it again only for the call that needs one.
177
+ struct VideoSurface {
178
+ IOSurfaceRef ios = nullptr; // nullptr once released
179
+ bool nv12 = true;
180
+ size_t width = 0, height = 0;
181
+ Colour colour;
182
+ int64_t bytes = 0;
183
+ };
184
+
185
+ void VideoSurfaceFree(Napi::Env env, VideoSurface* s) {
186
+ if (!s->ios) return;
187
+ CFRelease(s->ios);
188
+ s->ios = nullptr;
189
+ if (s->bytes) {
190
+ Napi::MemoryManagement::AdjustExternalMemory(env, -s->bytes);
191
+ s->bytes = 0;
192
+ }
193
+ }
194
+
195
+ bool IsVideoSurface(Napi::Value v) {
196
+ return v.IsExternal() &&
197
+ v.As<Napi::External<VideoSurface>>().CheckTypeTag(&kVideoSurfaceTag);
198
+ }
199
+
200
+ // The surface behind a handle, or nullptr with an error pending: not a
201
+ // video surface's handle, or one released.
202
+ VideoSurface* VideoSurfaceFrom(Napi::Value v, const char* verb) {
203
+ if (!IsVideoSurface(v)) {
204
+ Napi::TypeError::New(v.Env(), std::string(verb) +
205
+ ": expected a handle from "
206
+ "createVideoSurface")
207
+ .ThrowAsJavaScriptException();
208
+ return nullptr;
209
+ }
210
+ VideoSurface* s = v.As<Napi::External<VideoSurface>>().Data();
211
+ if (!s->ios) {
212
+ Napi::Error::New(v.Env(), std::string(verb) + ": video surface was released")
213
+ .ThrowAsJavaScriptException();
214
+ return nullptr;
215
+ }
216
+ return s;
217
+ }
218
+
219
+ // --- a frame's planes ---------------------------------------------------------
220
+
221
+ // One plane as handed over: its bytes, and how far apart its rows are.
222
+ struct Plane {
223
+ const uint8_t* data = nullptr;
224
+ size_t length = 0;
225
+ size_t stride = 0;
226
+ size_t rowBytes = 0; // what one row holds of the picture
227
+ size_t rows = 0;
228
+ };
229
+
230
+ // A frame of `format` at width x height: its planes out of `planes` (an
231
+ // array of Buffers or typed arrays) with `strides` (an array of numbers, or
232
+ // undefined for rows packed edge to edge), each checked to hold every row
233
+ // it claims. False, with a TypeError pending, otherwise.
234
+ bool ReadPlanes(Napi::Env env, const char* verb, Format format, size_t w,
235
+ size_t h, Napi::Value planesV, Napi::Value stridesV,
236
+ std::vector<Plane>* out) {
237
+ const size_t cw = (w + 1) / 2, ch = (h + 1) / 2;
238
+ std::vector<Plane> want;
239
+ switch (format) {
240
+ case Format::NV12:
241
+ want = {{nullptr, 0, 0, w, h}, {nullptr, 0, 0, cw * 2, ch}};
242
+ break;
243
+ case Format::I420:
244
+ want = {{nullptr, 0, 0, w, h}, {nullptr, 0, 0, cw, ch}, {nullptr, 0, 0, cw, ch}};
245
+ break;
246
+ case Format::BGRA:
247
+ want = {{nullptr, 0, 0, w * 4, h}};
248
+ break;
249
+ }
250
+ if (!planesV.IsArray() || planesV.As<Napi::Array>().Length() != want.size()) {
251
+ Napi::TypeError::New(env, std::string(verb) + ": a " + FormatName(format) +
252
+ " frame is an array of " +
253
+ std::to_string(want.size()) + " plane" +
254
+ (want.size() == 1 ? "" : "s"))
255
+ .ThrowAsJavaScriptException();
256
+ return false;
257
+ }
258
+ Napi::Array planes = planesV.As<Napi::Array>();
259
+ Napi::Array strides;
260
+ bool hasStrides = stridesV.IsArray();
261
+ if (hasStrides) strides = stridesV.As<Napi::Array>();
262
+ else if (!stridesV.IsUndefined() && !stridesV.IsNull()) {
263
+ Napi::TypeError::New(env, std::string(verb) + ": strides must be an array")
264
+ .ThrowAsJavaScriptException();
265
+ return false;
266
+ }
267
+ for (uint32_t i = 0; i < want.size(); i++) {
268
+ Plane& p = want[i];
269
+ Napi::Value pv = planes.Get(i);
270
+ if (pv.IsTypedArray()) {
271
+ Napi::TypedArray t = pv.As<Napi::TypedArray>();
272
+ p.data = (const uint8_t*)t.ArrayBuffer().Data() + t.ByteOffset();
273
+ p.length = t.ByteLength();
274
+ } else if (pv.IsArrayBuffer()) {
275
+ Napi::ArrayBuffer b = pv.As<Napi::ArrayBuffer>();
276
+ p.data = (const uint8_t*)b.Data();
277
+ p.length = b.ByteLength();
278
+ } else {
279
+ Napi::TypeError::New(env, std::string(verb) + ": plane " +
280
+ std::to_string(i) +
281
+ " is not a Buffer or a typed array")
282
+ .ThrowAsJavaScriptException();
283
+ return false;
284
+ }
285
+ p.stride = p.rowBytes;
286
+ if (hasStrides && i < strides.Length()) {
287
+ Napi::Value sv = strides.Get(i);
288
+ if (!sv.IsUndefined()) {
289
+ double sd = sv.IsNumber() ? sv.As<Napi::Number>().DoubleValue() : -1;
290
+ if (!(sd >= (double)p.rowBytes) || sd != (double)(size_t)sd) {
291
+ Napi::TypeError::New(env, std::string(verb) + ": the stride of plane " +
292
+ std::to_string(i) + " must be a whole number of at least " +
293
+ std::to_string(p.rowBytes))
294
+ .ThrowAsJavaScriptException();
295
+ return false;
296
+ }
297
+ p.stride = (size_t)sd;
298
+ }
299
+ }
300
+ size_t need = p.stride * (p.rows - 1) + p.rowBytes;
301
+ if (p.length < need) {
302
+ Napi::TypeError::New(env, std::string(verb) + ": plane " + std::to_string(i) +
303
+ " of a " + std::to_string(w) + "x" + std::to_string(h) +
304
+ " " + FormatName(format) + " frame needs " +
305
+ std::to_string(need) + " bytes, and has " +
306
+ std::to_string(p.length))
307
+ .ThrowAsJavaScriptException();
308
+ return false;
309
+ }
310
+ }
311
+ *out = std::move(want);
312
+ return true;
313
+ }
314
+
315
+ void CopyRows(uint8_t* dst, size_t dstStride, const Plane& p) {
316
+ for (size_t y = 0; y < p.rows; y++)
317
+ memcpy(dst + y * dstStride, p.data + y * p.stride, p.rowBytes);
318
+ }
319
+
320
+ // I420's two chroma planes into NV12's one, CbCr pairs.
321
+ void InterleaveRows(uint8_t* dst, size_t dstStride, const Plane& u, const Plane& v) {
322
+ for (size_t y = 0; y < u.rows; y++) {
323
+ uint8_t* d = dst + y * dstStride;
324
+ const uint8_t* cb = u.data + y * u.stride;
325
+ const uint8_t* cr = v.data + y * v.stride;
326
+ for (size_t x = 0; x < u.rowBytes; x++) {
327
+ d[2 * x] = cb[x];
328
+ d[2 * x + 1] = cr[x];
329
+ }
330
+ }
331
+ }
332
+
333
+ // BGRA rows with the alpha byte set: a frame is opaque, whatever a decoder
334
+ // left in its fourth byte, and a bitmap that is premultiplied would read a
335
+ // zero there as a hole.
336
+ void CopyOpaqueRows(uint8_t* dst, size_t dstStride, const Plane& p, size_t w) {
337
+ for (size_t y = 0; y < p.rows; y++) {
338
+ const uint8_t* s = p.data + y * p.stride;
339
+ uint8_t* d = dst + y * dstStride;
340
+ for (size_t x = 0; x < w; x++) {
341
+ uint32_t px;
342
+ memcpy(&px, s + 4 * x, 4);
343
+ px |= 0xff000000u;
344
+ memcpy(d + 4 * x, &px, 4);
345
+ }
346
+ }
347
+ }
348
+
349
+ // --- conversion ---------------------------------------------------------------
350
+ //
351
+ // Into a bitmap, a frame has to come out the colours Core Animation shows
352
+ // for the same frame on a layer, or a video moving between the two — which
353
+ // a renderer does whenever something is drawn over it — visibly changes
354
+ // shade. Since a surface is named the colour space its tags make
355
+ // (CALNameVideoColorSpace, below), Core Animation shows it as AVPlayerLayer
356
+ // shows a frame and as VideoToolbox's pixel transfer converts one, so the
357
+ // conversion is VideoToolbox's, colour-matched to sRGB, for every tagging.
358
+ // Measured on screen against a ramp and five hues (test/video-surface.js),
359
+ // the two agree to within two levels.
360
+ //
361
+ // What still differs is gamut: a layer keeps a colour that is outside sRGB
362
+ // and shows it on a wide-gamut panel, and an 8-bit sRGB bitmap clips it, so
363
+ // a saturated frame can lose a few levels in the drawn half.
364
+
365
+ // One per thread: a session is not safe to share across threads, and a
366
+ // worker's renderer converts on its own. Its destination is always plain
367
+ // memory (a BGRA video surface's is wrapped as bytes too): a session that
368
+ // has written into an IOSurface-backed buffer refuses
369
+ // (kVTPixelTransferNotSupportedErr) a three-plane frame into plain memory
370
+ // afterwards, and converts the same frame to other numbers.
371
+ thread_local VTPixelTransferSessionRef tlTransfer = nullptr;
372
+
373
+ VTPixelTransferSessionRef Transfer(bool fresh) {
374
+ if (tlTransfer && fresh) {
375
+ VTPixelTransferSessionInvalidate(tlTransfer);
376
+ CFRelease(tlTransfer);
377
+ tlTransfer = nullptr;
378
+ }
379
+ if (tlTransfer) return tlTransfer;
380
+ if (VTPixelTransferSessionCreate(kCFAllocatorDefault, &tlTransfer) != noErr) {
381
+ tlTransfer = nullptr;
382
+ return nullptr;
383
+ }
384
+ VTSessionSetProperty(tlTransfer, kVTPixelTransferPropertyKey_DestinationColorPrimaries,
385
+ kCVImageBufferColorPrimaries_ITU_R_709_2);
386
+ VTSessionSetProperty(tlTransfer, kVTPixelTransferPropertyKey_DestinationTransferFunction,
387
+ kCVImageBufferTransferFunction_sRGB);
388
+ VTSessionSetProperty(tlTransfer, kVTPixelTransferPropertyKey_RealTime, kCFBooleanTrue);
389
+ return tlTransfer;
390
+ }
391
+
392
+ bool ConvertMatched(Napi::Env env, const char* verb, Format format,
393
+ const std::vector<Plane>& planes, size_t w, size_t h, const Colour& colour,
394
+ uint8_t* dstData, size_t dstStride) {
395
+ OSType type = format == Format::NV12
396
+ ? (colour.full ? kCVPixelFormatType_420YpCbCr8BiPlanarFullRange
397
+ : kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange)
398
+ : (colour.full ? kCVPixelFormatType_420YpCbCr8PlanarFullRange
399
+ : kCVPixelFormatType_420YpCbCr8Planar);
400
+ size_t n = planes.size();
401
+ void* bases[3];
402
+ size_t widths[3], heights[3], bprs[3];
403
+ const size_t cw = (w + 1) / 2, ch = (h + 1) / 2;
404
+ for (size_t i = 0; i < n; i++) {
405
+ bases[i] = (void*)planes[i].data;
406
+ widths[i] = i == 0 ? w : cw;
407
+ heights[i] = i == 0 ? h : ch;
408
+ bprs[i] = planes[i].stride;
409
+ }
410
+ CVPixelBufferRef src = nullptr, dst = nullptr;
411
+ CVReturn rv = CVPixelBufferCreateWithPlanarBytes(
412
+ kCFAllocatorDefault, w, h, type, nullptr, 0, n, bases, widths, heights, bprs,
413
+ nullptr, nullptr, nullptr, &src);
414
+ if (rv == kCVReturnSuccess)
415
+ rv = CVPixelBufferCreateWithBytes(kCFAllocatorDefault, w, h, kCVPixelFormatType_32BGRA,
416
+ dstData, dstStride, nullptr, nullptr, nullptr, &dst);
417
+ if (rv != kCVReturnSuccess || !src || !dst) {
418
+ if (src) CVPixelBufferRelease(src);
419
+ if (dst) CVPixelBufferRelease(dst);
420
+ Napi::Error::New(env, std::string(verb) + ": could not wrap the frame (" +
421
+ std::to_string(rv) + ")")
422
+ .ThrowAsJavaScriptException();
423
+ return false;
424
+ }
425
+ Attach(src, colour);
426
+ AttachSRGB(dst);
427
+ VTPixelTransferSessionRef session = Transfer(false);
428
+ OSStatus st = session ? VTPixelTransferSessionTransferImage(session, src, dst) : -1;
429
+ if (st != noErr) {
430
+ // and once more on a session of its own, for whatever else a long-lived
431
+ // one turns out to remember
432
+ session = Transfer(true);
433
+ st = session ? VTPixelTransferSessionTransferImage(session, src, dst) : -1;
434
+ }
435
+ CVPixelBufferRelease(src);
436
+ CVPixelBufferRelease(dst);
437
+ if (st != noErr) {
438
+ Napi::Error::New(env, std::string(verb) + ": VideoToolbox could not convert the frame (" +
439
+ std::to_string(st) + ")")
440
+ .ThrowAsJavaScriptException();
441
+ return false;
442
+ }
443
+ return true;
444
+ }
445
+
446
+ // A YCbCr frame converted into BGRA rows at `dst`, opaque, in sRGB, the
447
+ // colours Core Animation shows it in on a layer. False with an error
448
+ // pending when the conversion was refused.
449
+ bool ConvertToBGRA(Napi::Env env, const char* verb, Format format,
450
+ const std::vector<Plane>& planes, size_t w, size_t h, const Colour& colour,
451
+ uint8_t* dst, size_t dstStride) {
452
+ return ConvertMatched(env, verb, format, planes, w, h, colour, dst, dstStride);
453
+ }
454
+
455
+ // --- verbs --------------------------------------------------------------------
456
+
457
+ Napi::Value CreateVideoSurface(const Napi::CallbackInfo& info) {
458
+ Napi::Env env = info.Env();
459
+ const char* verb = "createVideoSurface";
460
+ double wd = info[0].IsNumber() ? info[0].As<Napi::Number>().DoubleValue() : 0;
461
+ double hd = info[1].IsNumber() ? info[1].As<Napi::Number>().DoubleValue() : 0;
462
+ if (!(wd >= 1 && hd >= 1 && wd <= kMaxSide && hd <= kMaxSide) ||
463
+ wd != (double)(size_t)wd || hd != (double)(size_t)hd) {
464
+ Napi::TypeError::New(env, "createVideoSurface(width, height, options): width and "
465
+ "height are whole numbers of pixels, 1 to 16384")
466
+ .ThrowAsJavaScriptException();
467
+ return env.Undefined();
468
+ }
469
+ size_t w = (size_t)wd, h = (size_t)hd;
470
+ Format format = Format::NV12;
471
+ Colour colour;
472
+ if (info.Length() > 2 && info[2].IsObject()) {
473
+ Napi::Object o = info[2].As<Napi::Object>();
474
+ if (o.Has("format") && !o.Get("format").IsUndefined() &&
475
+ (!ParseFormat(o.Get("format"), &format) || format == Format::I420)) {
476
+ Napi::TypeError::New(env, "createVideoSurface: format must be 'NV12' or 'BGRA' "
477
+ "(an I420 frame is written into an NV12 surface)")
478
+ .ThrowAsJavaScriptException();
479
+ return env.Undefined();
480
+ }
481
+ if (!ParseColour(env, verb, o, &colour)) return env.Undefined();
482
+ }
483
+ bool nv12 = format == Format::NV12;
484
+ OSType type = nv12 ? (colour.full ? kCVPixelFormatType_420YpCbCr8BiPlanarFullRange
485
+ : kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange)
486
+ : kCVPixelFormatType_32BGRA;
487
+ NSDictionary* attrs = @{
488
+ (id)kCVPixelBufferIOSurfacePropertiesKey : @{},
489
+ (id)kCVPixelBufferPixelFormatTypeKey : @(type),
490
+ };
491
+ CVPixelBufferRef pb = nullptr;
492
+ CVReturn rv = CVPixelBufferCreate(kCFAllocatorDefault, w, h, type,
493
+ (__bridge CFDictionaryRef)attrs, &pb);
494
+ IOSurfaceRef ios = pb ? CVPixelBufferGetIOSurface(pb) : nullptr;
495
+ if (rv != kCVReturnSuccess || !ios) {
496
+ if (pb) CVPixelBufferRelease(pb);
497
+ Napi::Error::New(env, "createVideoSurface: CVPixelBufferCreate failed (" +
498
+ std::to_string(rv) + ")")
499
+ .ThrowAsJavaScriptException();
500
+ return env.Undefined();
501
+ }
502
+ // black, so a surface shown before its first frame shows no garbage
503
+ CVPixelBufferLockBaseAddress(pb, 0);
504
+ if (nv12) {
505
+ uint8_t* y = (uint8_t*)CVPixelBufferGetBaseAddressOfPlane(pb, 0);
506
+ memset(y, colour.full ? 0 : 16, CVPixelBufferGetBytesPerRowOfPlane(pb, 0) * h);
507
+ uint8_t* uv = (uint8_t*)CVPixelBufferGetBaseAddressOfPlane(pb, 1);
508
+ memset(uv, 128, CVPixelBufferGetBytesPerRowOfPlane(pb, 1) * ((h + 1) / 2));
509
+ } else {
510
+ uint8_t* p = (uint8_t*)CVPixelBufferGetBaseAddress(pb);
511
+ size_t bpr = CVPixelBufferGetBytesPerRow(pb);
512
+ for (size_t r = 0; r < h; r++) {
513
+ uint32_t* row = (uint32_t*)(p + r * bpr);
514
+ for (size_t x = 0; x < w; x++) row[x] = 0xff000000u;
515
+ }
516
+ }
517
+ CVPixelBufferUnlockBaseAddress(pb, 0);
518
+ if (nv12) {
519
+ // named the colour space these make when it is shown
520
+ // (setLayerContentsIOSurface, CALNameVideoColorSpace)
521
+ Attach(pb, colour);
522
+ } else {
523
+ // what is written into it is what an sRGB bitmap holds
524
+ AttachSRGB(pb);
525
+ CALNameSurfaceSRGB(ios, false);
526
+ }
527
+ CFRetain(ios);
528
+ CVPixelBufferRelease(pb);
529
+ auto* s = new VideoSurface();
530
+ s->ios = ios;
531
+ s->nv12 = nv12;
532
+ s->width = w;
533
+ s->height = h;
534
+ s->colour = colour;
535
+ s->bytes = (int64_t)IOSurfaceGetAllocSize(ios);
536
+ Napi::MemoryManagement::AdjustExternalMemory(env, s->bytes);
537
+ auto handle = Napi::External<VideoSurface>::New(env, s, [](Napi::Env e, VideoSurface* d) {
538
+ VideoSurfaceFree(e, d);
539
+ delete d;
540
+ });
541
+ handle.TypeTag(&kVideoSurfaceTag);
542
+ Napi::Object out = Napi::Object::New(env);
543
+ out.Set("handle", handle);
544
+ out.Set("iosurfaceId", (double)IOSurfaceGetID(ios));
545
+ return out;
546
+ }
547
+
548
+ Napi::Value WriteVideoSurface(const Napi::CallbackInfo& info) {
549
+ Napi::Env env = info.Env();
550
+ const char* verb = "writeVideoSurface";
551
+ Format format;
552
+ if (!ParseFormat(info[1], &format)) {
553
+ Napi::TypeError::New(env, "writeVideoSurface(target, format, planes, options): format "
554
+ "must be 'NV12', 'I420' or 'BGRA'")
555
+ .ThrowAsJavaScriptException();
556
+ return env.Undefined();
557
+ }
558
+ Napi::Object opts = info.Length() > 3 && info[3].IsObject() ? info[3].As<Napi::Object>()
559
+ : Napi::Object::New(env);
560
+ Napi::Value strides = opts.Has("strides") ? opts.Get("strides") : env.Undefined();
561
+ bool yuv = format != Format::BGRA;
562
+
563
+ if (IsVideoSurface(info[0])) {
564
+ VideoSurface* s = VideoSurfaceFrom(info[0], verb);
565
+ if (!s) return env.Undefined();
566
+ if (s->nv12 && !yuv) {
567
+ Napi::TypeError::New(env, "writeVideoSurface: an NV12 surface takes an NV12 or I420 "
568
+ "frame, not BGRA — make the surface with format 'BGRA'")
569
+ .ThrowAsJavaScriptException();
570
+ return env.Undefined();
571
+ }
572
+ std::vector<Plane> planes;
573
+ if (!ReadPlanes(env, verb, format, s->width, s->height, info[2], strides, &planes))
574
+ return env.Undefined();
575
+ if (!s->nv12 && yuv) {
576
+ // into a BGRA surface: converted, in the frame's own colour
577
+ Colour colour;
578
+ if (!ParseColour(env, verb, opts, &colour)) return env.Undefined();
579
+ IOSurfaceLock(s->ios, 0, nullptr);
580
+ ConvertToBGRA(env, verb, format, planes, s->width, s->height, colour,
581
+ (uint8_t*)IOSurfaceGetBaseAddress(s->ios), IOSurfaceGetBytesPerRow(s->ios));
582
+ IOSurfaceUnlock(s->ios, 0, nullptr);
583
+ return env.Undefined();
584
+ }
585
+ IOSurfaceLock(s->ios, 0, nullptr);
586
+ if (!s->nv12) {
587
+ CopyOpaqueRows((uint8_t*)IOSurfaceGetBaseAddress(s->ios),
588
+ IOSurfaceGetBytesPerRow(s->ios), planes[0], s->width);
589
+ } else {
590
+ CopyRows((uint8_t*)IOSurfaceGetBaseAddressOfPlane(s->ios, 0),
591
+ IOSurfaceGetBytesPerRowOfPlane(s->ios, 0), planes[0]);
592
+ uint8_t* uv = (uint8_t*)IOSurfaceGetBaseAddressOfPlane(s->ios, 1);
593
+ size_t bpr = IOSurfaceGetBytesPerRowOfPlane(s->ios, 1);
594
+ if (format == Format::NV12) CopyRows(uv, bpr, planes[1]);
595
+ else InterleaveRows(uv, bpr, planes[1], planes[2]);
596
+ }
597
+ IOSurfaceUnlock(s->ios, 0, nullptr);
598
+ return env.Undefined();
599
+ }
600
+
601
+ // a 2D surface: the frame at its top-left corner, `width` x `height` of it
602
+ CALSurfaceBits bits;
603
+ if (!CALSurfaceBitmap(info[0], &bits)) return env.Undefined();
604
+ size_t w = bits.width, h = bits.height;
605
+ for (const char* key : {"width", "height"}) {
606
+ if (!opts.Has(key) || opts.Get(key).IsUndefined()) continue;
607
+ Napi::Value v = opts.Get(key);
608
+ double d = v.IsNumber() ? v.As<Napi::Number>().DoubleValue() : 0;
609
+ size_t limit = key[0] == 'w' ? bits.width : bits.height;
610
+ if (!(d >= 1 && d <= (double)limit) || d != (double)(size_t)d) {
611
+ Napi::TypeError::New(env, std::string("writeVideoSurface: ") + key +
612
+ " must be a whole number of pixels, at most the "
613
+ "surface's " + std::to_string(limit))
614
+ .ThrowAsJavaScriptException();
615
+ return env.Undefined();
616
+ }
617
+ (key[0] == 'w' ? w : h) = (size_t)d;
618
+ }
619
+ std::vector<Plane> planes;
620
+ if (!ReadPlanes(env, verb, format, w, h, info[2], strides, &planes)) return env.Undefined();
621
+ if (!yuv) {
622
+ CopyOpaqueRows(bits.data, bits.bytesPerRow, planes[0], w);
623
+ return env.Undefined();
624
+ }
625
+ Colour colour;
626
+ if (!ParseColour(env, verb, opts, &colour)) return env.Undefined();
627
+ ConvertToBGRA(env, verb, format, planes, w, h, colour, bits.data, bits.bytesPerRow);
628
+ return env.Undefined();
629
+ }
630
+
631
+ Napi::Value VideoSurfaceIsInUse(const Napi::CallbackInfo& info) {
632
+ VideoSurface* s = VideoSurfaceFrom(info[0], "videoSurfaceIsInUse");
633
+ if (!s) return info.Env().Undefined();
634
+ return Napi::Boolean::New(info.Env(), IOSurfaceIsInUse(s->ios));
635
+ }
636
+
637
+ // Free the surface now rather than when the collector reaches the handle.
638
+ // A layer showing it keeps it alive until the layer lets it go. Idempotent.
639
+ Napi::Value ReleaseVideoSurface(const Napi::CallbackInfo& info) {
640
+ Napi::Env env = info.Env();
641
+ if (!IsVideoSurface(info[0])) {
642
+ Napi::TypeError::New(env, "releaseVideoSurface: expected a handle from createVideoSurface")
643
+ .ThrowAsJavaScriptException();
644
+ return env.Undefined();
645
+ }
646
+ VideoSurfaceFree(env, info[0].As<Napi::External<VideoSurface>>().Data());
647
+ return env.Undefined();
648
+ }
649
+
650
+ Napi::Value VideoFormats(const Napi::CallbackInfo& info) {
651
+ Napi::Env env = info.Env();
652
+ Napi::Object out = Napi::Object::New(env);
653
+ Napi::Array surfaces = Napi::Array::New(env, 2);
654
+ surfaces.Set(0u, "NV12");
655
+ surfaces.Set(1u, "BGRA");
656
+ Napi::Array frames = Napi::Array::New(env, 3);
657
+ frames.Set(0u, "NV12");
658
+ frames.Set(1u, "I420");
659
+ frames.Set(2u, "BGRA");
660
+ out.Set("surfaces", surfaces);
661
+ out.Set("frames", frames);
662
+ return out;
663
+ }
664
+
665
+ } // namespace
666
+
667
+ // Name `ios`'s colour space from the video tags CoreVideo writes onto a
668
+ // frame's IOSurface — its matrix, primaries and transfer function — as the
669
+ // space CoreVideo makes of them (CVImageBufferCreateColorSpaceFromAttachments).
670
+ // True when it named one; false for a surface with no such tags.
671
+ //
672
+ // Why a surface needs the space as well as the tags: shown with only the
673
+ // tags, Core Animation linearises a frame tagged BT.709 throughout with the
674
+ // exact 709 curve, while AVPlayerLayer — the platform's own player — shows
675
+ // the same frame through the space, on Apple's 1.961 gamma, as VideoToolbox's
676
+ // pixel transfer and Core Image convert it. A video-range grey of Y'=47 was
677
+ // sRGB 51 on a tagged layer and 40 under AVPlayerLayer (test/video-surface.js
678
+ // and test/player.js hold both to the player's). Named, a frame on a layer,
679
+ // the same frame drawn into a bitmap, and AVPlayerLayer playing it agree.
680
+ bool CALNameVideoColorSpace(IOSurfaceRef ios) {
681
+ if (!ios) return false;
682
+ CFTypeRef primaries = IOSurfaceCopyValue(ios, CFSTR("IOSurfaceColorPrimaries"));
683
+ if (!primaries) return false;
684
+ CFTypeRef matrix = IOSurfaceCopyValue(ios, CFSTR("IOSurfaceYCbCrMatrix"));
685
+ CFTypeRef transfer = IOSurfaceCopyValue(ios, CFSTR("IOSurfaceTransferFunction"));
686
+ NSMutableDictionary* tags = [NSMutableDictionary dictionary];
687
+ tags[(id)kCVImageBufferColorPrimariesKey] = (__bridge id)primaries;
688
+ if (matrix) tags[(id)kCVImageBufferYCbCrMatrixKey] = (__bridge id)matrix;
689
+ if (transfer) tags[(id)kCVImageBufferTransferFunctionKey] = (__bridge id)transfer;
690
+ CGColorSpaceRef cs = CVImageBufferCreateColorSpaceFromAttachments((__bridge CFDictionaryRef)tags);
691
+ CFRelease(primaries);
692
+ if (matrix) CFRelease(matrix);
693
+ if (transfer) CFRelease(transfer);
694
+ if (!cs) return false;
695
+ CFPropertyListRef named = CGColorSpaceCopyPropertyList(cs);
696
+ CGColorSpaceRelease(cs);
697
+ if (!named) return false;
698
+ IOSurfaceSetValue(ios, kIOSurfaceColorSpace, named);
699
+ CFRelease(named);
700
+ return true;
701
+ }
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
+
797
+ void InitVideo(Napi::Env env, Napi::Object exports) {
798
+ exports.Set("createVideoSurface", Napi::Function::New(env, CreateVideoSurface));
799
+ exports.Set("writeVideoSurface", Napi::Function::New(env, WriteVideoSurface));
800
+ exports.Set("videoSurfaceIsInUse", Napi::Function::New(env, VideoSurfaceIsInUse));
801
+ exports.Set("releaseVideoSurface", Napi::Function::New(env, ReleaseVideoSurface));
802
+ exports.Set("videoFormats", Napi::Function::New(env, VideoFormats));
803
+ }