Raw ↗
+ +
9a12521 fix(ci): resolve windows strcasecmp linkage and macos test failures
saifmukhtar · 2026-11-24
1 /*
2 * SPDX-License-Identifier: AGPL-3.0-or-later WITH Classpath-exception-2.0
3 * Copyright (c) 2026 Saif Mukhtar
4 *
5 * OpenAVX - Open Audio-Video eXchange
6 * src/avx_video_vt.c - macOS VideoToolbox Hardware Video Decoder Backend
7 */
8  
9 #include "avx_video_codec.h"
10 #include "avx_internal.h"
11 #include "avx_rtsp.h"
12 #include "avx_color.h"
13  
14 #if defined(AVX_OS_MACOS)
15  
16 #include <CoreFoundation/CoreFoundation.h>
17 #include <CoreMedia/CoreMedia.h>
18 #include <CoreVideo/CoreVideo.h>
19 #include <VideoToolbox/VideoToolbox.h>
20 #include <stdlib.h>
21 #include <string.h>
22  
23 typedef struct {
24 uint32_t src_fourcc;
25 uint32_t width;
26 uint32_t height;
27  
28 CMVideoFormatDescriptionRef fmt_desc;
29 VTDecompressionSessionRef session;
30  
31 uint8_t *vps;
32 size_t vps_len;
33 uint8_t *sps;
34 size_t sps_len;
35 uint8_t *pps;
36 size_t pps_len;
37 uint8_t *av1_seq;
38 size_t av1_seq_len;
39  
40 uint8_t *avcc_buf;
41 size_t avcc_cap;
42  
43 bool has_frame;
44 bool cb_error;
45 uint32_t out_width;
46 uint32_t out_height;
47 uint8_t *frame_buf;
48 size_t frame_buf_size;
49 } avx_vt_dec_ctx_t;
50  
51 static void vt_replace_buf(uint8_t **dst, size_t *dst_len, const uint8_t *src, size_t src_len, bool *changed) {
52 if (!src || src_len == 0) return;
53 if (*dst && *dst_len == src_len && memcmp(*dst, src, src_len) == 0) return;
54 uint8_t *nb = (uint8_t *)malloc(src_len);
55 if (!nb) return;
56 memcpy(nb, src, src_len);
57 free(*dst);
58 *dst = nb;
59 *dst_len = src_len;
60 if (changed) *changed = true;
61 }
62  
63 static bool vt_probe_av1_available(void) {
64 if (__builtin_available(macOS 13.0, *)) {
65 if (!VTIsHardwareDecodeSupported(kCMVideoCodecType_AV1)) return false;
66 CMVideoFormatDescriptionRef fmt = NULL;
67 OSStatus st = CMVideoFormatDescriptionCreate(kCFAllocatorDefault, kCMVideoCodecType_AV1, 128, 128, NULL, &fmt);
68 if (st != noErr || !fmt) return false;
69 VTDecompressionSessionRef sess = NULL;
70 VTDecompressionOutputCallbackRecord cb = {0};
71 st = VTDecompressionSessionCreate(kCFAllocatorDefault, fmt, NULL, NULL, &cb, &sess);
72 CFRelease(fmt);
73 if (st == noErr && sess) {
74 VTDecompressionSessionInvalidate(sess);
75 CFRelease(sess);
76 return true;
77 }
78 }
79 return false;
80 }
81  
82 static bool vt_dec_supports_fourcc(uint32_t src_fourcc) {
83 if (src_fourcc == OAVX_FOURCC_VIDEO_TYPE_H264 || src_fourcc == 0x34363268 ||
84 src_fourcc == OAVX_FOURCC_VIDEO_TYPE_HEVC || src_fourcc == 0x43564568) {
85 return true;
86 }
87 if (src_fourcc == OAVX_FOURCC_VIDEO_TYPE_AV01) {
88 return vt_probe_av1_available();
89 }
90 return false;
91 }
92  
93 static void vt_release_session(avx_vt_dec_ctx_t *ctx) {
94 if (ctx->session) {
95 VTDecompressionSessionWaitForAsynchronousFrames(ctx->session);
96 VTDecompressionSessionInvalidate(ctx->session);
97 CFRelease(ctx->session);
98 ctx->session = NULL;
99 }
100 if (ctx->fmt_desc) {
101 CFRelease(ctx->fmt_desc);
102 ctx->fmt_desc = NULL;
103 }
104 }
105  
106 static void vt_dec_destroy(void *backend_ctx) {
107 avx_vt_dec_ctx_t *ctx = (avx_vt_dec_ctx_t *)backend_ctx;
108 if (!ctx) return;
109  
110 vt_release_session(ctx);
111 free(ctx->vps);
112 free(ctx->sps);
113 free(ctx->pps);
114 free(ctx->av1_seq);
115 free(ctx->avcc_buf);
116 free(ctx->frame_buf);
117 free(ctx);
118 }
119  
120 static void vt_output_callback(
121 void *decompressionOutputRefCon,
122 void *sourceFrameRefCon,
123 OSStatus status,
124 VTDecodeInfoFlags infoFlags,
125 CVImageBufferRef imageBuffer,
126 CMTime presentationTimeStamp,
127 CMTime presentationDuration)
128 {
129 (void)sourceFrameRefCon;
130 (void)infoFlags;
131 (void)presentationTimeStamp;
132 (void)presentationDuration;
133  
134 avx_vt_dec_ctx_t *ctx = (avx_vt_dec_ctx_t *)decompressionOutputRefCon;
135 if (!ctx) return;
136  
137 if (status != noErr || !imageBuffer) {
138 if (status != noErr) ctx->cb_error = true;
139 return;
140 }
141  
142 if (CVPixelBufferLockBaseAddress(imageBuffer, kCVPixelBufferLock_ReadOnly) != kCVReturnSuccess) {
143 ctx->cb_error = true;
144 return;
145 }
146  
147 uint32_t w = (uint32_t)CVPixelBufferGetWidth(imageBuffer);
148 uint32_t h = (uint32_t)CVPixelBufferGetHeight(imageBuffer);
149 uint64_t need_u64 = (uint64_t)w * (uint64_t)h * 2ULL;
150  
151 if (w > 0 && h > 0 && w <= AVX_MAX_VIDEO_WIDTH && h <= AVX_MAX_VIDEO_HEIGHT &&
152 need_u64 <= AVX_MAX_DECOMPRESSED_FRAME_SIZE &&
153 CVPixelBufferIsPlanar(imageBuffer) && CVPixelBufferGetPlaneCount(imageBuffer) >= 2) {
154 uint32_t ch = (h + 1U) / 2U;
155 size_t need = (size_t)w * (size_t)h + (size_t)w * (size_t)ch;
156 if (ctx->frame_buf_size < need) {
157 uint8_t *nb = (uint8_t *)realloc(ctx->frame_buf, need);
158 if (nb) {
159 ctx->frame_buf = nb;
160 ctx->frame_buf_size = need;
161 }
162 }
163 if (ctx->frame_buf && ctx->frame_buf_size >= need) {
164 const uint8_t *y_src = (const uint8_t *)CVPixelBufferGetBaseAddressOfPlane(imageBuffer, 0);
165 const uint8_t *uv_src = (const uint8_t *)CVPixelBufferGetBaseAddressOfPlane(imageBuffer, 1);
166 size_t y_stride = CVPixelBufferGetBytesPerRowOfPlane(imageBuffer, 0);
167 size_t uv_stride = CVPixelBufferGetBytesPerRowOfPlane(imageBuffer, 1);
168  
169 if (y_src && uv_src && y_stride >= w && uv_stride >= w) {
170 for (uint32_t y = 0; y < h; ++y) {
171 memcpy(ctx->frame_buf + (size_t)y * w, y_src + (size_t)y * y_stride, w);
172 }
173 uint8_t *dst_uv = ctx->frame_buf + (size_t)w * h;
174 for (uint32_t y = 0; y < ch; ++y) {
175 memcpy(dst_uv + (size_t)y * w, uv_src + (size_t)y * uv_stride, w);
176 }
177 ctx->out_width = w;
178 ctx->out_height = h;
179 ctx->has_frame = true;
180 }
181 }
182 }
183  
184 CVPixelBufferUnlockBaseAddress(imageBuffer, kCVPixelBufferLock_ReadOnly);
185 }
186  
187 /* Allocates or re-creates Apple VTDecompressionSession bound to CoreVideo pixel buffer attributes. */
188 static int vt_ensure_session(avx_vt_dec_ctx_t *ctx, CMVideoFormatDescriptionRef new_fmt) {
189 if (!new_fmt) return -1;
190  
191 if (ctx->session && VTDecompressionSessionCanAcceptFormatDescription(ctx->session, new_fmt)) {
192 if (ctx->fmt_desc) CFRelease(ctx->fmt_desc);
193 ctx->fmt_desc = new_fmt;
194 return 0;
195 }
196  
197 vt_release_session(ctx);
198 ctx->fmt_desc = new_fmt;
199  
200 CFMutableDictionaryRef decoder_spec = CFDictionaryCreateMutable(
201 kCFAllocatorDefault, 1, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
202 if (decoder_spec) {
203 if (__builtin_available(macOS 10.9, *)) {
204 CFDictionarySetValue(decoder_spec,
205 kVTVideoDecoderSpecification_EnableHardwareAcceleratedVideoDecoder,
206 kCFBooleanTrue);
207 }
208 }
209  
210 CFMutableDictionaryRef dst_attrs = CFDictionaryCreateMutable(
211 kCFAllocatorDefault, 1, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
212 if (dst_attrs) {
213 int32_t nv12_fmt = (int32_t)kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange;
214 CFNumberRef pix_num = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &nv12_fmt);
215 if (pix_num) {
216 CFDictionarySetValue(dst_attrs, kCVPixelBufferPixelFormatTypeKey, pix_num);
217 CFRelease(pix_num);
218 }
219 }
220  
221 VTDecompressionOutputCallbackRecord cb_rec = {
222 .decompressionOutputCallback = vt_output_callback,
223 .decompressionOutputRefCon = ctx
224 };
225  
226 OSStatus st = VTDecompressionSessionCreate(
227 kCFAllocatorDefault,
228 ctx->fmt_desc,
229 decoder_spec,
230 dst_attrs,
231 &cb_rec,
232 &ctx->session);
233 if (st != noErr && decoder_spec) {
234 /* Retry without hardware requirement if hardware decoder block is absent */
235 st = VTDecompressionSessionCreate(
236 kCFAllocatorDefault,
237 ctx->fmt_desc,
238 NULL,
239 dst_attrs,
240 &cb_rec,
241 &ctx->session);
242 }
243  
244 if (decoder_spec) CFRelease(decoder_spec);
245 if (dst_attrs) CFRelease(dst_attrs);
246  
247 if (st != noErr || !ctx->session) {
248 vt_release_session(ctx);
249 return -1;
250 }
251 return 0;
252 }
253  
254 /* Creates CMVideoFormatDescription from in-band parameter sets (VPS/SPS/PPS) for VideoToolbox. */
255 static int vt_rebuild_h264_hevc_format(avx_vt_dec_ctx_t *ctx, bool is_hevc) {
256 if (!ctx->sps || !ctx->pps) return -1;
257  
258 CMVideoFormatDescriptionRef new_fmt = NULL;
259 OSStatus st = -1;
260 if (!is_hevc) {
261 const uint8_t *ptrs[2] = { ctx->sps, ctx->pps };
262 size_t sizes[2] = { ctx->sps_len, ctx->pps_len };
263 st = CMVideoFormatDescriptionCreateFromH264ParameterSets(
264 kCFAllocatorDefault, 2, ptrs, sizes, 4, &new_fmt);
265 } else {
266 if (!ctx->vps) return -1;
267 const uint8_t *ptrs[3] = { ctx->vps, ctx->sps, ctx->pps };
268 size_t sizes[3] = { ctx->vps_len, ctx->sps_len, ctx->pps_len };
269 st = CMVideoFormatDescriptionCreateFromHEVCParameterSets(
270 kCFAllocatorDefault, 3, ptrs, sizes, 4, NULL, &new_fmt);
271 }
272 if (st != noErr || !new_fmt) {
273 if (new_fmt) CFRelease(new_fmt);
274 return -1;
275 }
276 return vt_ensure_session(ctx, new_fmt);
277 }
278  
279 static int vt_rebuild_av1_format(avx_vt_dec_ctx_t *ctx, const uint8_t *seq_obu, size_t seq_len) {
280 if (!seq_obu || seq_len == 0) return -1;
281  
282 int w = (int)ctx->width;
283 int h = (int)ctx->height;
284 int prof = 0, lvl = 0;
285 avx_rtsp_parse_sequence_header_av1(seq_obu, seq_len, &w, &h, &prof, &lvl);
286 if (w <= 0 || h <= 0) return -1;
287 ctx->width = (uint32_t)w;
288 ctx->height = (uint32_t)h;
289  
290 size_t av1c_len = 4 + seq_len;
291 uint8_t *av1c = (uint8_t *)malloc(av1c_len);
292 if (!av1c) return -1;
293 av1c[0] = 0x81;
294 av1c[1] = (uint8_t)(((prof & 0x07) << 5) | (lvl & 0x1F));
295 av1c[2] = 0x00;
296 av1c[3] = 0x00;
297 memcpy(av1c + 4, seq_obu, seq_len);
298  
299 CFDataRef av1c_data = CFDataCreate(kCFAllocatorDefault, av1c, (CFIndex)av1c_len);
300 free(av1c);
301 if (!av1c_data) return -1;
302  
303 CFMutableDictionaryRef atoms = CFDictionaryCreateMutable(
304 kCFAllocatorDefault, 1, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
305 CFMutableDictionaryRef exts = CFDictionaryCreateMutable(
306 kCFAllocatorDefault, 1, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
307  
308 CMVideoFormatDescriptionRef new_fmt = NULL;
309 if (atoms && exts) {
310 CFStringRef key_av1c = CFSTR("av1C");
311 CFDictionarySetValue(atoms, key_av1c, av1c_data);
312 CFDictionarySetValue(exts, kCMFormatDescriptionExtension_SampleDescriptionExtensionAtoms, atoms);
313 CMVideoFormatDescriptionCreate(
314 kCFAllocatorDefault, kCMVideoCodecType_AV1, w, h, exts, &new_fmt);
315 }
316  
317 if (atoms) CFRelease(atoms);
318 if (exts) CFRelease(exts);
319 CFRelease(av1c_data);
320  
321 if (!new_fmt) return -1;
322 return vt_ensure_session(ctx, new_fmt);
323 }
324  
325 static int vt_dec_create(const avx_video_dec_cfg_t *cfg, void **backend_ctx) {
326 if (!cfg || !backend_ctx || !vt_dec_supports_fourcc(cfg->fourcc)) return -1;
327  
328 avx_vt_dec_ctx_t *ctx = (avx_vt_dec_ctx_t *)calloc(1, sizeof(*ctx));
329 if (!ctx) return -1;
330  
331 ctx->src_fourcc = cfg->fourcc;
332 ctx->width = cfg->width ? cfg->width : 1920;
333 ctx->height = cfg->height ? cfg->height : 1080;
334 *backend_ctx = ctx;
335 return 0;
336 }
337  
338 static int vt_decode_sample_buffer(avx_vt_dec_ctx_t *ctx, const uint8_t *sample_bytes, size_t sample_len,
339 oavx_video_frame_t *out_frame)
340 {
341 if (!ctx->session || !ctx->fmt_desc || sample_len == 0) {
342 return AVX_VIDEO_CODEC_NEED_MORE_DATA;
343 }
344  
345 CMBlockBufferRef block_buf = NULL;
346 OSStatus st = CMBlockBufferCreateWithMemoryBlock(
347 kCFAllocatorDefault,
348 (void *)sample_bytes,
349 sample_len,
350 kCFAllocatorNull,
351 NULL,
352 0,
353 sample_len,
354 0,
355 &block_buf);
356 if (st != noErr || !block_buf) {
357 if (block_buf) CFRelease(block_buf);
358 return AVX_VIDEO_CODEC_ERROR;
359 }
360  
361 CMSampleBufferRef sample_buf = NULL;
362 st = CMSampleBufferCreateReady(
363 kCFAllocatorDefault,
364 block_buf,
365 ctx->fmt_desc,
366 1,
367 0,
368 NULL,
369 1,
370 &sample_len,
371 &sample_buf);
372 CFRelease(block_buf);
373 if (st != noErr || !sample_buf) {
374 if (sample_buf) CFRelease(sample_buf);
375 return AVX_VIDEO_CODEC_ERROR;
376 }
377  
378 ctx->has_frame = false;
379 ctx->cb_error = false;
380 st = VTDecompressionSessionDecodeFrame(ctx->session, sample_buf, 0, NULL, NULL);
381 CFRelease(sample_buf);
382  
383 if (st != noErr || ctx->cb_error) {
384 return AVX_VIDEO_CODEC_ERROR;
385 }
386 if (!ctx->has_frame) {
387 return AVX_VIDEO_CODEC_NEED_MORE_DATA;
388 }
389  
390 uint32_t w = ctx->out_width;
391 uint32_t h = ctx->out_height;
392 out_frame->fourcc = OAVX_FOURCC_VIDEO_TYPE_NV12;
393 out_frame->width = w;
394 out_frame->height = h;
395 out_frame->planes[0] = ctx->frame_buf;
396 out_frame->strides[0] = w;
397 out_frame->planes[1] = ctx->frame_buf + (size_t)w * h;
398 out_frame->strides[1] = w;
399 out_frame->planes[2] = NULL;
400 out_frame->strides[2] = 0;
401 out_frame->planes[3] = NULL;
402 out_frame->strides[3] = 0;
403 return AVX_VIDEO_CODEC_OK;
404 }
405  
406 /* Packages Annex-B NAL stream into CMSampleBuffer and feeds VideoToolbox hardware decompression. */
407 static int vt_dec_decode(void *backend_ctx,
408 const uint8_t *pkt_data, size_t pkt_size,
409 oavx_video_frame_t *out_frame)
410 {
411 avx_vt_dec_ctx_t *ctx = (avx_vt_dec_ctx_t *)backend_ctx;
412 if (!ctx || !pkt_data || pkt_size == 0 || !out_frame) {
413 return AVX_VIDEO_CODEC_ERROR;
414 }
415  
416 if (ctx->src_fourcc == OAVX_FOURCC_VIDEO_TYPE_AV01) {
417 size_t pos = 0;
418 if (pkt_size >= 4 && pkt_data[0] == 0 && pkt_data[1] == 0) {
419 if (pkt_data[2] == 1) pos = 3;
420 else if (pkt_data[2] == 0 && pkt_data[3] == 1) pos = 4;
421 }
422 while (pos < pkt_size) {
423 size_t obu_start = pos;
424 uint8_t header = pkt_data[pos++];
425 int obu_type = (header >> 3) & 0x0F;
426 if (header & 0x04) {
427 if (pos >= pkt_size) break;
428 pos++;
429 }
430 size_t obu_len = pkt_size - pos;
431 if (header & 0x02) {
432 size_t val = 0, shift = 0;
433 while (pos < pkt_size) {
434 uint8_t b = pkt_data[pos++];
435 val |= (size_t)(b & 0x7F) << shift;
436 if (!(b & 0x80)) break;
437 shift += 7;
438 }
439 obu_len = val;
440 }
441 if (pos + obu_len > pkt_size) break;
442 if (obu_type == 1) {
443 size_t seq_sz = (pos + obu_len) - obu_start;
444 bool seq_changed = false;
445 vt_replace_buf(&ctx->av1_seq, &ctx->av1_seq_len, pkt_data + obu_start, seq_sz, &seq_changed);
446 if (!ctx->session || seq_changed) {
447 if (vt_rebuild_av1_format(ctx, ctx->av1_seq, ctx->av1_seq_len) != 0) {
448 return AVX_VIDEO_CODEC_ERROR;
449 }
450 }
451 break;
452 }
453 if (!(header & 0x02)) break; /* Stop if OBU does not have an explicit length field */
454 pos += obu_len;
455 }
456 if (!ctx->session) {
457 return AVX_VIDEO_CODEC_NEED_MORE_DATA;
458 }
459 return vt_decode_sample_buffer(ctx, pkt_data, pkt_size, out_frame);
460 }
461  
462 bool is_hevc = (ctx->src_fourcc == OAVX_FOURCC_VIDEO_TYPE_HEVC || ctx->src_fourcc == 0x43564568);
463  
464 size_t max_avcc = pkt_size + 256;
465 if (ctx->avcc_cap < max_avcc) {
466 uint8_t *nb = (uint8_t *)realloc(ctx->avcc_buf, max_avcc);
467 if (!nb) return AVX_VIDEO_CODEC_ERROR;
468 ctx->avcc_buf = nb;
469 ctx->avcc_cap = max_avcc;
470 }
471  
472 bool params_changed = false;
473 bool saw_start_code = false;
474 size_t avcc_len = 0;
475 size_t pos = 0;
476  
477 while (pos < pkt_size) {
478 size_t sc_len = 0;
479 if (pos + 3 <= pkt_size && pkt_data[pos] == 0 && pkt_data[pos + 1] == 0) {
480 if (pkt_data[pos + 2] == 1) sc_len = 3;
481 else if (pos + 4 <= pkt_size && pkt_data[pos + 2] == 0 && pkt_data[pos + 3] == 1) sc_len = 4;
482 }
483  
484 size_t nalu_start;
485 size_t next_pos;
486 if (sc_len > 0) {
487 saw_start_code = true;
488 nalu_start = pos + sc_len;
489 next_pos = nalu_start;
490 while (next_pos + 3 <= pkt_size) {
491 if (pkt_data[next_pos] == 0 && pkt_data[next_pos + 1] == 0 &&
492 (pkt_data[next_pos + 2] == 1 ||
493 (next_pos + 4 <= pkt_size && pkt_data[next_pos + 2] == 0 && pkt_data[next_pos + 3] == 1))) {
494 break;
495 }
496 next_pos++;
497 }
498 if (next_pos + 3 > pkt_size) next_pos = pkt_size;
499 } else if (!saw_start_code && pos == 0) {
500 nalu_start = 0;
501 next_pos = pkt_size;
502 } else {
503 pos++;
504 continue;
505 }
506  
507 size_t nlen = next_pos - nalu_start;
508 if (nlen > 0) {
509 const uint8_t *np = pkt_data + nalu_start;
510 bool is_param = false;
511 if (!is_hevc) {
512 uint8_t ntype = np[0] & 0x1F;
513 if (ntype == 7) { vt_replace_buf(&ctx->sps, &ctx->sps_len, np, nlen, &params_changed); is_param = true; }
514 else if (ntype == 8) { vt_replace_buf(&ctx->pps, &ctx->pps_len, np, nlen, &params_changed); is_param = true; }
515 } else {
516 uint8_t ntype = (np[0] >> 1) & 0x3F;
517 if (ntype == 32) { vt_replace_buf(&ctx->vps, &ctx->vps_len, np, nlen, &params_changed); is_param = true; }
518 else if (ntype == 33) { vt_replace_buf(&ctx->sps, &ctx->sps_len, np, nlen, &params_changed); is_param = true; }
519 else if (ntype == 34) { vt_replace_buf(&ctx->pps, &ctx->pps_len, np, nlen, &params_changed); is_param = true; }
520 }
521  
522 if (!is_param && avcc_len + 4 + nlen <= ctx->avcc_cap) {
523 ctx->avcc_buf[avcc_len + 0] = (uint8_t)((nlen >> 24) & 0xFF);
524 ctx->avcc_buf[avcc_len + 1] = (uint8_t)((nlen >> 16) & 0xFF);
525 ctx->avcc_buf[avcc_len + 2] = (uint8_t)((nlen >> 8) & 0xFF);
526 ctx->avcc_buf[avcc_len + 3] = (uint8_t)(nlen & 0xFF);
527 memcpy(ctx->avcc_buf + avcc_len + 4, np, nlen);
528 avcc_len += 4 + nlen;
529 }
530 }
531 pos = next_pos;
532 }
533  
534 if ((params_changed || !ctx->session) && ctx->sps && ctx->pps && (!is_hevc || ctx->vps)) {
535 if (vt_rebuild_h264_hevc_format(ctx, is_hevc) != 0) {
536 return AVX_VIDEO_CODEC_ERROR;
537 }
538 }
539  
540 if (!ctx->session || avcc_len == 0) {
541 return AVX_VIDEO_CODEC_NEED_MORE_DATA;
542 }
543  
544 return vt_decode_sample_buffer(ctx, ctx->avcc_buf, avcc_len, out_frame);
545 }
546  
547 static void vt_dec_reset(void *backend_ctx) {
548 avx_vt_dec_ctx_t *ctx = (avx_vt_dec_ctx_t *)backend_ctx;
549 if (!ctx || !ctx->session) return;
550 VTDecompressionSessionWaitForAsynchronousFrames(ctx->session);
551 }
552  
553 static const avx_video_decoder_ops_t s_vt_decoder_ops = {
554 .name = "videotoolbox",
555 .priority = 90,
556 .is_hardware = true,
557 .supports_fourcc = vt_dec_supports_fourcc,
558 .create = vt_dec_create,
559 .decode = vt_dec_decode,
560 .reset = vt_dec_reset,
561 .destroy = vt_dec_destroy
562 };
563  
564 const avx_video_decoder_ops_t *avx_video_vt_get_ops(void) {
565 return &s_vt_decoder_ops;
566 }
567  
568 /* ========================================================================= */
569 /* VideoToolbox Hardware Video Encoder Backend */
570 /* ========================================================================= */
571  
572 typedef struct {
573 uint32_t target_fourcc;
574 uint32_t width;
575 uint32_t height;
576 int32_t fps_num;
577 int32_t fps_den;
578 uint32_t bitrate_kbps;
579 uint8_t quality;
580 int64_t frame_count;
581  
582 VTCompressionSessionRef session;
583 bool force_keyframe;
584  
585 uint8_t *out_buf;
586 size_t out_cap;
587 size_t out_size;
588 bool out_is_keyframe;
589 bool encode_error;
590  
591 uint8_t *tmp_buf;
592 size_t tmp_cap;
593 } avx_vt_enc_ctx_t;
594  
595 static void vt_compression_output_callback(
596 void *outputCallbackRefCon,
597 void *sourceFrameRefCon,
598 OSStatus status,
599 VTEncodeInfoFlags infoFlags,
600 CMSampleBufferRef sampleBuffer)
601 {
602 (void)sourceFrameRefCon;
603 (void)infoFlags;
604 avx_vt_enc_ctx_t *ctx = (avx_vt_enc_ctx_t *)outputCallbackRefCon;
605 if (!ctx) return;
606 if (status != noErr || !sampleBuffer) {
607 ctx->encode_error = true;
608 return;
609 }
610  
611 bool is_key = false;
612 CFArrayRef attachments = CMSampleBufferGetSampleAttachmentsArray(sampleBuffer, false);
613 if (attachments && CFArrayGetCount(attachments) > 0) {
614 CFDictionaryRef dict = (CFDictionaryRef)CFArrayGetValueAtIndex(attachments, 0);
615 is_key = !CFDictionaryContainsKey(dict, kCMSampleAttachmentKey_NotSync);
616 }
617  
618 size_t write_pos = 0;
619  
620 /* On keyframe, prepend parameter sets (VPS/SPS/PPS) in Annex-B format */
621 if (is_key) {
622 CMFormatDescriptionRef fmt = CMSampleBufferGetFormatDescription(sampleBuffer);
623 if (fmt) {
624 if (ctx->target_fourcc == OAVX_FOURCC_VIDEO_TYPE_H264) {
625 size_t sps_count = 0;
626 const uint8_t *sps = NULL;
627 size_t sps_size = 0;
628 const uint8_t *pps = NULL;
629 size_t pps_size = 0;
630 if (CMVideoFormatDescriptionGetH264ParameterSetAtIndex(fmt, 0, &sps, &sps_size, &sps_count, NULL) == noErr && sps && sps_size > 0) {
631 if (write_pos + 4 + sps_size <= ctx->out_cap) {
632 ctx->out_buf[write_pos++] = 0;
633 ctx->out_buf[write_pos++] = 0;
634 ctx->out_buf[write_pos++] = 0;
635 ctx->out_buf[write_pos++] = 1;
636 memcpy(ctx->out_buf + write_pos, sps, sps_size);
637 write_pos += sps_size;
638 }
639 }
640 if (CMVideoFormatDescriptionGetH264ParameterSetAtIndex(fmt, 1, &pps, &pps_size, &sps_count, NULL) == noErr && pps && pps_size > 0) {
641 if (write_pos + 4 + pps_size <= ctx->out_cap) {
642 ctx->out_buf[write_pos++] = 0;
643 ctx->out_buf[write_pos++] = 0;
644 ctx->out_buf[write_pos++] = 0;
645 ctx->out_buf[write_pos++] = 1;
646 memcpy(ctx->out_buf + write_pos, pps, pps_size);
647 write_pos += pps_size;
648 }
649 }
650 } else if (ctx->target_fourcc == OAVX_FOURCC_VIDEO_TYPE_HEVC) {
651 size_t param_count = 0;
652 if (CMVideoFormatDescriptionGetHEVCParameterSetAtIndex(fmt, 0, NULL, NULL, &param_count, NULL) == noErr) {
653 for (size_t i = 0; i < param_count; ++i) {
654 const uint8_t *param_ptr = NULL;
655 size_t param_size = 0;
656 if (CMVideoFormatDescriptionGetHEVCParameterSetAtIndex(fmt, i, &param_ptr, &param_size, NULL, NULL) == noErr && param_ptr && param_size > 0) {
657 if (write_pos + 4 + param_size <= ctx->out_cap) {
658 ctx->out_buf[write_pos++] = 0;
659 ctx->out_buf[write_pos++] = 0;
660 ctx->out_buf[write_pos++] = 0;
661 ctx->out_buf[write_pos++] = 1;
662 memcpy(ctx->out_buf + write_pos, param_ptr, param_size);
663 write_pos += param_size;
664 }
665 }
666 }
667 }
668 }
669 }
670 }
671  
672 /* Extract slice NALs from CMBlockBuffer and convert AVCC to Annex-B */
673 CMBlockBufferRef block_buf = CMSampleBufferGetDataBuffer(sampleBuffer);
674 if (block_buf) {
675 size_t total_len = CMBlockBufferGetDataLength(block_buf);
676 char *data_ptr = NULL;
677 CMBlockBufferRef contig_buf = NULL;
678 if (CMBlockBufferGetDataPointer(block_buf, 0, NULL, NULL, &data_ptr) != noErr || !data_ptr) {
679 if (CMBlockBufferCreateContiguous(kCFAllocatorDefault, block_buf, kCFAllocatorDefault, NULL, 0, 0, 0, &contig_buf) == noErr) {
680 CMBlockBufferGetDataPointer(contig_buf, 0, NULL, NULL, &data_ptr);
681 }
682 }
683  
684 if (data_ptr) {
685 size_t offset = 0;
686 while (offset + 4 <= total_len) {
687 uint32_t nal_len = ((uint32_t)(uint8_t)data_ptr[offset + 0] << 24) |
688 ((uint32_t)(uint8_t)data_ptr[offset + 1] << 16) |
689 ((uint32_t)(uint8_t)data_ptr[offset + 2] << 8) |
690 ((uint32_t)(uint8_t)data_ptr[offset + 3]);
691 offset += 4;
692 if (offset + nal_len > total_len) break;
693  
694 if (write_pos + 4 + nal_len <= ctx->out_cap) {
695 ctx->out_buf[write_pos++] = 0;
696 ctx->out_buf[write_pos++] = 0;
697 ctx->out_buf[write_pos++] = 0;
698 ctx->out_buf[write_pos++] = 1;
699 memcpy(ctx->out_buf + write_pos, data_ptr + offset, nal_len);
700 write_pos += nal_len;
701 }
702 offset += nal_len;
703 }
704 }
705 if (contig_buf) CFRelease(contig_buf);
706 }
707  
708 ctx->out_size = write_pos;
709 ctx->out_is_keyframe = is_key;
710 }
711  
712 static bool vt_enc_supports_fourcc(uint32_t target_fourcc) {
713 return (target_fourcc == OAVX_FOURCC_VIDEO_TYPE_H264 ||
714 target_fourcc == OAVX_FOURCC_VIDEO_TYPE_HEVC);
715 }
716  
717 /* Configures Apple VTCompressionSession for real-time low-latency hardware H.264/HEVC encoding. */
718 static int vt_enc_create(const avx_video_enc_cfg_t *cfg, void **backend_ctx) {
719 if (!cfg || !backend_ctx || !vt_enc_supports_fourcc(cfg->fourcc)) return -1;
720 if (cfg->width == 0 || cfg->height == 0 ||
721 cfg->width > AVX_MAX_VIDEO_WIDTH || cfg->height > AVX_MAX_VIDEO_HEIGHT) {
722 return -1;
723 }
724  
725 avx_vt_enc_ctx_t *ctx = (avx_vt_enc_ctx_t *)calloc(1, sizeof(*ctx));
726 if (!ctx) return -1;
727  
728 ctx->target_fourcc = cfg->fourcc;
729 ctx->width = cfg->width;
730 ctx->height = cfg->height;
731 ctx->fps_num = cfg->fps_num > 0 ? cfg->fps_num : 60;
732 ctx->fps_den = cfg->fps_den > 0 ? cfg->fps_den : 1;
733 ctx->bitrate_kbps = cfg->bitrate_kbps;
734 ctx->quality = cfg->quality;
735  
736 CMVideoCodecType codec_type = (cfg->fourcc == OAVX_FOURCC_VIDEO_TYPE_HEVC)
737 ? kCMVideoCodecType_HEVC
738 : kCMVideoCodecType_H264;
739  
740 OSStatus status = VTCompressionSessionCreate(
741 kCFAllocatorDefault,
742 (int32_t)cfg->width,
743 (int32_t)cfg->height,
744 codec_type,
745 NULL,
746 NULL,
747 kCFAllocatorDefault,
748 vt_compression_output_callback,
749 ctx,
750 &ctx->session
751 );
752 if (status != noErr || !ctx->session) {
753 free(ctx);
754 return -1;
755 }
756  
757 /* Low-latency broadcast properties */
758 VTSessionSetProperty(ctx->session, kVTCompressionPropertyKey_RealTime, kCFBooleanTrue);
759 VTSessionSetProperty(ctx->session, kVTCompressionPropertyKey_AllowFrameReordering, kCFBooleanFalse);
760  
761 if (cfg->fourcc == OAVX_FOURCC_VIDEO_TYPE_H264) {
762 VTSessionSetProperty(ctx->session, kVTCompressionPropertyKey_ProfileLevel, kVTProfileLevel_H264_High_AutoLevel);
763 } else {
764 VTSessionSetProperty(ctx->session, kVTCompressionPropertyKey_ProfileLevel, kVTProfileLevel_HEVC_Main_AutoLevel);
765 }
766  
767 /* Framerate */
768 float fps = (float)ctx->fps_num / (float)ctx->fps_den;
769 CFNumberRef fps_num = CFNumberCreate(kCFAllocatorDefault, kCFNumberFloatType, &fps);
770 if (fps_num) {
771 VTSessionSetProperty(ctx->session, kVTCompressionPropertyKey_ExpectedFrameRate, fps_num);
772 CFRelease(fps_num);
773 }
774  
775 /* Bitrate */
776 int32_t br_bps = 0;
777 if (cfg->bitrate_kbps > 0) {
778 br_bps = (int32_t)(cfg->bitrate_kbps * 1000U);
779 } else {
780 uint64_t pixels = (uint64_t)cfg->width * cfg->height;
781 if (pixels >= 3840ULL * 2160ULL) br_bps = 35000000;
782 else if (pixels >= 1920ULL * 1080ULL) br_bps = 12000000;
783 else br_bps = 6000000;
784 }
785 CFNumberRef br_num = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &br_bps);
786 if (br_num) {
787 VTSessionSetProperty(ctx->session, kVTCompressionPropertyKey_AverageBitRate, br_num);
788 CFRelease(br_num);
789 }
790  
791 /* Keyframe interval */
792 int32_t kf_int = cfg->keyframe_interval > 0 ? (int32_t)cfg->keyframe_interval : (int32_t)(fps * 2.0f);
793 if (kf_int <= 0) kf_int = 60;
794 CFNumberRef kf_num = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &kf_int);
795 if (kf_num) {
796 VTSessionSetProperty(ctx->session, kVTCompressionPropertyKey_MaxKeyFrameInterval, kf_num);
797 CFRelease(kf_num);
798 }
799  
800 VTCompressionSessionPrepareToEncodeFrames(ctx->session);
801 *backend_ctx = ctx;
802 return 0;
803 }
804  
805 static CVPixelBufferRef vt_enc_wrap_pixel_buffer(avx_vt_enc_ctx_t *ctx, const oavx_video_frame_t *in, uint32_t w, uint32_t h) {
806 if (!in || !in->planes[0]) return NULL;
807  
808 CVPixelBufferRef px_buf = NULL;
809 if (in->fourcc == OAVX_FOURCC_VIDEO_TYPE_UYVY) {
810 size_t stride = in->strides[0] ? in->strides[0] : (size_t)w * 2ULL;
811 CVPixelBufferCreateWithBytes(
812 kCFAllocatorDefault, w, h,
813 kCVPixelFormatType_422YpCbCr8,
814 in->planes[0], stride,
815 NULL, NULL, NULL, &px_buf
816 );
817 } else if (in->fourcc == OAVX_FOURCC_VIDEO_TYPE_NV12) {
818 void *ptrs[2] = { in->planes[0], in->planes[1] ? in->planes[1] : (in->planes[0] + (size_t)w * h) };
819 size_t widths[2] = { w, (w + 1U) / 2U };
820 size_t heights[2] = { h, (h + 1U) / 2U };
821 size_t strides[2] = {
822 in->strides[0] ? in->strides[0] : (size_t)w,
823 in->strides[1] ? in->strides[1] : (size_t)w
824 };
825 CVPixelBufferCreateWithPlanarBytes(
826 kCFAllocatorDefault, w, h,
827 kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange,
828 NULL, 0,
829 2, ptrs, widths, heights, strides,
830 NULL, NULL, NULL, &px_buf
831 );
832 } else if (in->fourcc == OAVX_FOURCC_VIDEO_TYPE_P216) {
833 if (ctx && ctx->target_fourcc == OAVX_FOURCC_VIDEO_TYPE_H264) {
834 size_t needed = (size_t)w * (size_t)h * 2ULL;
835 if (ctx->tmp_cap < needed) {
836 uint8_t *nb = (uint8_t *)realloc(ctx->tmp_buf, needed);
837 if (!nb) return NULL;
838 ctx->tmp_buf = nb;
839 ctx->tmp_cap = needed;
840 }
841 avx_color_p216_to_uyvy(in->planes[0], ctx->tmp_buf, (int)w, (int)h);
842 CVPixelBufferCreateWithBytes(
843 kCFAllocatorDefault, w, h,
844 kCVPixelFormatType_422YpCbCr8,
845 ctx->tmp_buf, (size_t)w * 2ULL,
846 NULL, NULL, NULL, &px_buf
847 );
848 } else {
849 void *ptrs[2] = { in->planes[0], in->planes[1] ? in->planes[1] : (in->planes[0] + (size_t)w * h * 2ULL) };
850 size_t widths[2] = { w, (w + 1U) / 2U };
851 size_t heights[2] = { h, h };
852 size_t strides[2] = {
853 in->strides[0] ? in->strides[0] : (size_t)w * 2ULL,
854 in->strides[1] ? in->strides[1] : (size_t)w * 2ULL
855 };
856 CVPixelBufferCreateWithPlanarBytes(
857 kCFAllocatorDefault, w, h,
858 kCVPixelFormatType_422YpCbCr10BiPlanarVideoRange,
859 NULL, 0,
860 2, ptrs, widths, heights, strides,
861 NULL, NULL, NULL, &px_buf
862 );
863 }
864 } else if (in->fourcc == OAVX_FOURCC_VIDEO_TYPE_BGRA || in->fourcc == OAVX_FOURCC_VIDEO_TYPE_BGRX) {
865 size_t stride = in->strides[0] ? in->strides[0] : (size_t)w * 4ULL;
866 CVPixelBufferCreateWithBytes(
867 kCFAllocatorDefault, w, h,
868 kCVPixelFormatType_32BGRA,
869 in->planes[0], stride,
870 NULL, NULL, NULL, &px_buf
871 );
872 } else if (in->fourcc == OAVX_FOURCC_VIDEO_TYPE_RGBA || in->fourcc == OAVX_FOURCC_VIDEO_TYPE_RGBX) {
873 if (ctx) {
874 size_t needed = (size_t)w * (size_t)h * 4ULL;
875 if (ctx->tmp_cap < needed) {
876 uint8_t *nb = (uint8_t *)realloc(ctx->tmp_buf, needed);
877 if (!nb) return NULL;
878 ctx->tmp_buf = nb;
879 ctx->tmp_cap = needed;
880 }
881 avx_color_rgba_to_bgra(in->planes[0], ctx->tmp_buf, (int)w, (int)h);
882 CVPixelBufferCreateWithBytes(
883 kCFAllocatorDefault, w, h,
884 kCVPixelFormatType_32BGRA,
885 ctx->tmp_buf, (size_t)w * 4ULL,
886 NULL, NULL, NULL, &px_buf
887 );
888 }
889 } else if (in->fourcc == OAVX_FOURCC_VIDEO_TYPE_I420 || in->fourcc == OAVX_FOURCC_VIDEO_TYPE_YV12) {
890 uint32_t cw = (w + 1U) / 2U;
891 uint32_t ch = (h + 1U) / 2U;
892 void *ptrs[3] = {
893 in->planes[0],
894 in->planes[1] ? in->planes[1] : (in->planes[0] + (size_t)w * h),
895 in->planes[2] ? in->planes[2] : (in->planes[0] + (size_t)w * h + (size_t)cw * ch)
896 };
897 size_t widths[3] = { w, cw, cw };
898 size_t heights[3] = { h, ch, ch };
899 size_t strides[3] = {
900 in->strides[0] ? in->strides[0] : (size_t)w,
901 in->strides[1] ? in->strides[1] : (size_t)cw,
902 in->strides[2] ? in->strides[2] : (size_t)cw
903 };
904 CVPixelBufferCreateWithPlanarBytes(
905 kCFAllocatorDefault, w, h,
906 kCVPixelFormatType_420YpCbCr8Planar,
907 NULL, 0,
908 3, ptrs, widths, heights, strides,
909 NULL, NULL, NULL, &px_buf
910 );
911 }
912 return px_buf;
913 }
914  
915 /* Wraps input frame in CVPixelBufferRef, submits to VTCompressionSession, and drains NAL packets. */
916 static int vt_enc_encode(void *backend_ctx,
917 const oavx_video_frame_t *in_frame,
918 uint8_t *out_buf, size_t out_cap,
919 size_t *out_size, bool *out_is_keyframe)
920 {
921 avx_vt_enc_ctx_t *ctx = (avx_vt_enc_ctx_t *)backend_ctx;
922 if (!ctx || !ctx->session || !in_frame || !out_buf || !out_size || out_cap < 16) {
923 return AVX_VIDEO_CODEC_ERROR;
924 }
925  
926 uint32_t w = in_frame->width ? in_frame->width : ctx->width;
927 uint32_t h = in_frame->height ? in_frame->height : ctx->height;
928 if (w != ctx->width || h != ctx->height) {
929 return AVX_VIDEO_CODEC_ERROR;
930 }
931  
932 CVPixelBufferRef px_buf = vt_enc_wrap_pixel_buffer(ctx, in_frame, w, h);
933 if (!px_buf) {
934 return AVX_VIDEO_CODEC_ERROR;
935 }
936  
937 ctx->out_buf = out_buf;
938 ctx->out_cap = out_cap;
939 ctx->out_size = 0;
940 ctx->out_is_keyframe = false;
941 ctx->encode_error = false;
942  
943 CMTime pts = CMTimeMake(ctx->frame_count++, ctx->fps_den > 0 ? (ctx->fps_num / ctx->fps_den) : 30);
944  
945 CFDictionaryRef frame_props = NULL;
946 if (ctx->force_keyframe) {
947 const void *keys[] = { kVTEncodeFrameOptionKey_ForceKeyFrame };
948 const void *vals[] = { kCFBooleanTrue };
949 frame_props = CFDictionaryCreate(
950 kCFAllocatorDefault, keys, vals, 1,
951 &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks
952 );
953 ctx->force_keyframe = false;
954 }
955  
956 VTEncodeInfoFlags flags = 0;
957 OSStatus st = VTCompressionSessionEncodeFrame(
958 ctx->session,
959 px_buf,
960 pts,
961 kCMTimeInvalid,
962 frame_props,
963 NULL,
964 &flags
965 );
966 if (frame_props) CFRelease(frame_props);
967 CVPixelBufferRelease(px_buf);
968  
969 if (st != noErr) {
970 return AVX_VIDEO_CODEC_ERROR;
971 }
972  
973 /* Synchronously complete pending frames for immediate zero-delay output */
974 VTCompressionSessionCompleteFrames(ctx->session, kCMTimeInvalid);
975  
976 if (ctx->encode_error || ctx->out_size == 0) {
977 return AVX_VIDEO_CODEC_ERROR;
978 }
979  
980 *out_size = ctx->out_size;
981 if (out_is_keyframe) *out_is_keyframe = ctx->out_is_keyframe;
982 return AVX_VIDEO_CODEC_OK;
983 }
984  
985 static int vt_enc_set_quality(void *backend_ctx, uint8_t quality) {
986 avx_vt_enc_ctx_t *ctx = (avx_vt_enc_ctx_t *)backend_ctx;
987 if (!ctx || !ctx->session) return -1;
988 ctx->quality = quality;
989 float q = (float)quality / 100.0f;
990 CFNumberRef q_num = CFNumberCreate(kCFAllocatorDefault, kCFNumberFloatType, &q);
991 if (q_num) {
992 VTSessionSetProperty(ctx->session, kVTCompressionPropertyKey_Quality, q_num);
993 CFRelease(q_num);
994 }
995 return 0;
996 }
997  
998 static void vt_enc_request_keyframe(void *backend_ctx) {
999 avx_vt_enc_ctx_t *ctx = (avx_vt_enc_ctx_t *)backend_ctx;
1000 if (ctx) ctx->force_keyframe = true;
1001 }
1002  
1003 static void vt_enc_destroy(void *backend_ctx) {
1004 avx_vt_enc_ctx_t *ctx = (avx_vt_enc_ctx_t *)backend_ctx;
1005 if (!ctx) return;
1006 if (ctx->session) {
1007 VTCompressionSessionInvalidate(ctx->session);
1008 CFRelease(ctx->session);
1009 ctx->session = NULL;
1010 }
1011 if (ctx->tmp_buf) {
1012 free(ctx->tmp_buf);
1013 ctx->tmp_buf = NULL;
1014 }
1015 free(ctx);
1016 }
1017  
1018 static const avx_video_encoder_ops_t s_vt_encoder_ops = {
1019 .name = "videotoolbox",
1020 .priority = 90,
1021 .is_hardware = true,
1022 .supports_fourcc = vt_enc_supports_fourcc,
1023 .create = vt_enc_create,
1024 .encode = vt_enc_encode,
1025 .set_quality = vt_enc_set_quality,
1026 .request_keyframe = vt_enc_request_keyframe,
1027 .destroy = vt_enc_destroy
1028 };
1029  
1030 const avx_video_encoder_ops_t *avx_video_vt_get_encoder_ops(void) {
1031 return &s_vt_encoder_ops;
1032 }
1033  
1034 #else
1035  
1036 const avx_video_decoder_ops_t *avx_video_vt_get_ops(void) {
1037 return NULL;
1038 }
1039  
1040 const avx_video_encoder_ops_t *avx_video_vt_get_encoder_ops(void) {
1041 return NULL;
1042 }
1043  
1044 #endif /* AVX_OS_MACOS */