screencapturekit 2.1.0

Safe Rust bindings for Apple's ScreenCaptureKit framework - screen and audio capture on macOS
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// CoreMedia Bridge - CMSampleBuffer, CMTime, CMFormatDescription, CMBlockBuffer

import CoreMedia
import CoreVideo
import Foundation
import ScreenCaptureKit

// MARK: - Audio Buffer List Bridge Types

public struct AudioBufferBridge {
    public var number_channels: UInt32
    public var data_bytes_size: UInt32
    public var data_ptr: UnsafeMutableRawPointer?
}

public struct AudioBufferListRaw {
    public var num_buffers: UInt32
    public var buffers_ptr: UnsafeMutablePointer<AudioBufferBridge>?
    public var buffers_len: UInt
}

// MARK: - CMSampleBuffer Bridge

@_cdecl("cm_sample_buffer_get_image_buffer")
public func cm_sample_buffer_get_image_buffer(_ sampleBuffer: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer? {
    let buffer = Unmanaged<CMSampleBuffer>.fromOpaque(sampleBuffer).takeUnretainedValue()
    guard let imageBuffer = CMSampleBufferGetImageBuffer(buffer) else {
        return nil
    }
    return Unmanaged.passRetained(imageBuffer).toOpaque()
}

@_cdecl("cm_sample_buffer_get_frame_status")
public func cm_sample_buffer_get_frame_status(_ sampleBuffer: UnsafeMutableRawPointer) -> Int32 {
    let buffer = Unmanaged<CMSampleBuffer>.fromOpaque(sampleBuffer).takeUnretainedValue()

    guard let attachments = CMSampleBufferGetSampleAttachmentsArray(buffer, createIfNecessary: false) as? [[CFString: Any]],
          let firstAttachment = attachments.first,
          let status = firstAttachment[SCStreamFrameInfo.status.rawValue as CFString] as? SCFrameStatus
    else {
        return -1
    }

    return Int32(status.rawValue)
}

@_cdecl("cm_sample_buffer_get_display_time")
public func cm_sample_buffer_get_display_time(_ sampleBuffer: UnsafeMutableRawPointer, _ outValue: UnsafeMutablePointer<UInt64>) -> Bool {
    let buffer = Unmanaged<CMSampleBuffer>.fromOpaque(sampleBuffer).takeUnretainedValue()

    guard let attachments = CMSampleBufferGetSampleAttachmentsArray(buffer, createIfNecessary: false) as? [[CFString: Any]],
          let firstAttachment = attachments.first,
          let displayTime = firstAttachment[SCStreamFrameInfo.displayTime.rawValue as CFString] as? UInt64
    else {
        return false
    }

    outValue.pointee = displayTime
    return true
}

@_cdecl("cm_sample_buffer_get_scale_factor")
public func cm_sample_buffer_get_scale_factor(_ sampleBuffer: UnsafeMutableRawPointer, _ outValue: UnsafeMutablePointer<Float64>) -> Bool {
    let buffer = Unmanaged<CMSampleBuffer>.fromOpaque(sampleBuffer).takeUnretainedValue()

    guard let attachments = CMSampleBufferGetSampleAttachmentsArray(buffer, createIfNecessary: false) as? [[CFString: Any]],
          let firstAttachment = attachments.first,
          let scaleFactor = firstAttachment[SCStreamFrameInfo.scaleFactor.rawValue as CFString] as? Float64
    else {
        return false
    }

    outValue.pointee = scaleFactor
    return true
}

@_cdecl("cm_sample_buffer_get_content_scale")
public func cm_sample_buffer_get_content_scale(_ sampleBuffer: UnsafeMutableRawPointer, _ outValue: UnsafeMutablePointer<Float64>) -> Bool {
    let buffer = Unmanaged<CMSampleBuffer>.fromOpaque(sampleBuffer).takeUnretainedValue()

    guard let attachments = CMSampleBufferGetSampleAttachmentsArray(buffer, createIfNecessary: false) as? [[CFString: Any]],
          let firstAttachment = attachments.first,
          let contentScale = firstAttachment[SCStreamFrameInfo.contentScale.rawValue as CFString] as? Float64
    else {
        return false
    }

    outValue.pointee = contentScale
    return true
}

@_cdecl("cm_sample_buffer_get_content_rect")
public func cm_sample_buffer_get_content_rect(_ sampleBuffer: UnsafeMutableRawPointer, _ outX: UnsafeMutablePointer<Float64>, _ outY: UnsafeMutablePointer<Float64>, _ outWidth: UnsafeMutablePointer<Float64>, _ outHeight: UnsafeMutablePointer<Float64>) -> Bool {
    let buffer = Unmanaged<CMSampleBuffer>.fromOpaque(sampleBuffer).takeUnretainedValue()

    guard let attachments = CMSampleBufferGetSampleAttachmentsArray(buffer, createIfNecessary: false) as? [[CFString: Any]],
          let firstAttachment = attachments.first,
          let rectDict = firstAttachment[SCStreamFrameInfo.contentRect.rawValue as CFString] as? [String: Any],
          let rect = CGRect(dictionaryRepresentation: rectDict as CFDictionary)
    else {
        return false
    }

    outX.pointee = rect.origin.x
    outY.pointee = rect.origin.y
    outWidth.pointee = rect.size.width
    outHeight.pointee = rect.size.height
    return true
}

@available(macOS 14.0, *)
@_cdecl("cm_sample_buffer_get_bounding_rect")
public func cm_sample_buffer_get_bounding_rect(_ sampleBuffer: UnsafeMutableRawPointer, _ outX: UnsafeMutablePointer<Float64>, _ outY: UnsafeMutablePointer<Float64>, _ outWidth: UnsafeMutablePointer<Float64>, _ outHeight: UnsafeMutablePointer<Float64>) -> Bool {
    let buffer = Unmanaged<CMSampleBuffer>.fromOpaque(sampleBuffer).takeUnretainedValue()

    guard let attachments = CMSampleBufferGetSampleAttachmentsArray(buffer, createIfNecessary: false) as? [[CFString: Any]],
          let firstAttachment = attachments.first,
          let rectDict = firstAttachment[SCStreamFrameInfo.boundingRect.rawValue as CFString] as? [String: Any],
          let rect = CGRect(dictionaryRepresentation: rectDict as CFDictionary)
    else {
        return false
    }

    outX.pointee = rect.origin.x
    outY.pointee = rect.origin.y
    outWidth.pointee = rect.size.width
    outHeight.pointee = rect.size.height
    return true
}

@available(macOS 13.1, *)
@_cdecl("cm_sample_buffer_get_screen_rect")
public func cm_sample_buffer_get_screen_rect(_ sampleBuffer: UnsafeMutableRawPointer, _ outX: UnsafeMutablePointer<Float64>, _ outY: UnsafeMutablePointer<Float64>, _ outWidth: UnsafeMutablePointer<Float64>, _ outHeight: UnsafeMutablePointer<Float64>) -> Bool {
    let buffer = Unmanaged<CMSampleBuffer>.fromOpaque(sampleBuffer).takeUnretainedValue()

    guard let attachments = CMSampleBufferGetSampleAttachmentsArray(buffer, createIfNecessary: false) as? [[CFString: Any]],
          let firstAttachment = attachments.first,
          let rectDict = firstAttachment[SCStreamFrameInfo.screenRect.rawValue as CFString] as? [String: Any],
          let rect = CGRect(dictionaryRepresentation: rectDict as CFDictionary)
    else {
        return false
    }

    outX.pointee = rect.origin.x
    outY.pointee = rect.origin.y
    outWidth.pointee = rect.size.width
    outHeight.pointee = rect.size.height
    return true
}

/// Read the `SCStreamFrameInfo.presenterOverlayContentRect` attachment off the
/// sample buffer (macOS 14.2+ Presenter Overlay). Returns false (and leaves the
/// out parameters untouched) if the attachment is missing — typical when the
/// stream was not configured with a presenter overlay.
@available(macOS 14.2, *)
@_cdecl("cm_sample_buffer_get_presenter_overlay_content_rect")
public func cm_sample_buffer_get_presenter_overlay_content_rect(_ sampleBuffer: UnsafeMutableRawPointer, _ outX: UnsafeMutablePointer<Float64>, _ outY: UnsafeMutablePointer<Float64>, _ outWidth: UnsafeMutablePointer<Float64>, _ outHeight: UnsafeMutablePointer<Float64>) -> Bool {
    let buffer = Unmanaged<CMSampleBuffer>.fromOpaque(sampleBuffer).takeUnretainedValue()

    guard let attachments = CMSampleBufferGetSampleAttachmentsArray(buffer, createIfNecessary: false) as? [[CFString: Any]],
          let firstAttachment = attachments.first,
          let rectDict = firstAttachment[SCStreamFrameInfo.presenterOverlayContentRect.rawValue as CFString] as? [String: Any],
          let rect = CGRect(dictionaryRepresentation: rectDict as CFDictionary)
    else {
        return false
    }

    outX.pointee = rect.origin.x
    outY.pointee = rect.origin.y
    outWidth.pointee = rect.size.width
    outHeight.pointee = rect.size.height
    return true
}

@_cdecl("cm_sample_buffer_get_dirty_rects")
public func cm_sample_buffer_get_dirty_rects(_ sampleBuffer: UnsafeMutableRawPointer, _ outRects: UnsafeMutablePointer<UnsafeMutableRawPointer?>, _ outCount: UnsafeMutablePointer<Int>) -> Bool {
    let buffer = Unmanaged<CMSampleBuffer>.fromOpaque(sampleBuffer).takeUnretainedValue()

    guard let attachments = CMSampleBufferGetSampleAttachmentsArray(buffer, createIfNecessary: false) as? [[CFString: Any]],
          let firstAttachment = attachments.first,
          let dirtyRects = firstAttachment[SCStreamFrameInfo.dirtyRects.rawValue as CFString] as? [Any]
    else {
        outRects.pointee = nil
        outCount.pointee = 0
        return false
    }

    var rects: [CGRect] = []
    for item in dirtyRects {
        if let rectDict = item as? [String: Any],
           let rect = CGRect(dictionaryRepresentation: rectDict as CFDictionary)
        {
            rects.append(rect)
        }
    }

    guard !rects.isEmpty else {
        outRects.pointee = nil
        outCount.pointee = 0
        return false
    }

    // Allocate array of 4 doubles per rect (x, y, width, height)
    let rectsPtr = UnsafeMutablePointer<Float64>.allocate(capacity: rects.count * 4)
    for (index, rect) in rects.enumerated() {
        rectsPtr[index * 4 + 0] = rect.origin.x
        rectsPtr[index * 4 + 1] = rect.origin.y
        rectsPtr[index * 4 + 2] = rect.size.width
        rectsPtr[index * 4 + 3] = rect.size.height
    }

    outRects.pointee = UnsafeMutableRawPointer(rectsPtr)
    outCount.pointee = rects.count
    return true
}

@_cdecl("cm_sample_buffer_free_dirty_rects")
public func cm_sample_buffer_free_dirty_rects(_ rectsPtr: UnsafeMutableRawPointer) {
    rectsPtr.deallocate()
}

// Bit flags identifying which fields the batched frame_info FFI managed to
// populate. Keep in sync with `FrameInfoFields` in src/cm/ffi.rs.
private struct FrameInfoFieldBits {
    static let status: UInt32 = 1 << 0
    static let displayTime: UInt32 = 1 << 1
    static let scaleFactor: UInt32 = 1 << 2
    static let contentScale: UInt32 = 1 << 3
    static let contentRect: UInt32 = 1 << 4
    static let boundingRect: UInt32 = 1 << 5
    static let screenRect: UInt32 = 1 << 6
    static let presenterOverlayRect: UInt32 = 1 << 7
}

// Single-call frame info fetch.
//
// Replaces 5+ separate `cm_sample_buffer_get_*` calls that each invoked
// `CMSampleBufferGetSampleAttachmentsArray` and re-bridged the dictionary
// from CF → Swift. Measured at ~11.4 µs/frame with the old per-attribute
// path; this collapses to one attachment fetch + one Swift bridging cast
// (~3 µs) by reading every documented `SCStreamFrameInfo` key into a single
// `repr(C)` out struct.
//
// `presenterOverlayContentRect` is read on macOS 14.2+ only; the field stays
// at its default value and the corresponding bit is left clear on older
// systems.
//
// Layout MUST match `FrameInfoRaw` in src/cm/ffi.rs.
@_cdecl("cm_sample_buffer_get_frame_info")
public func cm_sample_buffer_get_frame_info(
    _ sampleBuffer: UnsafeMutableRawPointer,
    _ outFields: UnsafeMutablePointer<UInt32>,
    _ outStatus: UnsafeMutablePointer<Int32>,
    _ outDisplayTime: UnsafeMutablePointer<UInt64>,
    _ outScaleFactor: UnsafeMutablePointer<Float64>,
    _ outContentScale: UnsafeMutablePointer<Float64>,
    _ outContentRect: UnsafeMutablePointer<Float64>,        // [4]: x,y,w,h
    _ outBoundingRect: UnsafeMutablePointer<Float64>,       // [4]
    _ outScreenRect: UnsafeMutablePointer<Float64>,         // [4]
    _ outPresenterOverlayRect: UnsafeMutablePointer<Float64> // [4]
) -> Bool {
    let buffer = Unmanaged<CMSampleBuffer>.fromOpaque(sampleBuffer).takeUnretainedValue()
    outFields.pointee = 0

    guard let attachments = CMSampleBufferGetSampleAttachmentsArray(buffer, createIfNecessary: false) as? [[CFString: Any]],
          let attachment = attachments.first
    else {
        return false
    }

    var fields: UInt32 = 0

    if let status = attachment[SCStreamFrameInfo.status.rawValue as CFString] as? SCFrameStatus {
        outStatus.pointee = Int32(status.rawValue)
        fields |= FrameInfoFieldBits.status
    }
    if let displayTime = attachment[SCStreamFrameInfo.displayTime.rawValue as CFString] as? UInt64 {
        outDisplayTime.pointee = displayTime
        fields |= FrameInfoFieldBits.displayTime
    }
    if let scaleFactor = attachment[SCStreamFrameInfo.scaleFactor.rawValue as CFString] as? Float64 {
        outScaleFactor.pointee = scaleFactor
        fields |= FrameInfoFieldBits.scaleFactor
    }
    if let contentScale = attachment[SCStreamFrameInfo.contentScale.rawValue as CFString] as? Float64 {
        outContentScale.pointee = contentScale
        fields |= FrameInfoFieldBits.contentScale
    }
    if let dict = attachment[SCStreamFrameInfo.contentRect.rawValue as CFString] as? [String: Any],
       let rect = CGRect(dictionaryRepresentation: dict as CFDictionary) {
        outContentRect[0] = rect.origin.x
        outContentRect[1] = rect.origin.y
        outContentRect[2] = rect.size.width
        outContentRect[3] = rect.size.height
        fields |= FrameInfoFieldBits.contentRect
    }
    if #available(macOS 14.0, *),
       let dict = attachment[SCStreamFrameInfo.boundingRect.rawValue as CFString] as? [String: Any],
       let rect = CGRect(dictionaryRepresentation: dict as CFDictionary) {
        outBoundingRect[0] = rect.origin.x
        outBoundingRect[1] = rect.origin.y
        outBoundingRect[2] = rect.size.width
        outBoundingRect[3] = rect.size.height
        fields |= FrameInfoFieldBits.boundingRect
    }
    if #available(macOS 13.1, *),
       let dict = attachment[SCStreamFrameInfo.screenRect.rawValue as CFString] as? [String: Any],
       let rect = CGRect(dictionaryRepresentation: dict as CFDictionary) {
        outScreenRect[0] = rect.origin.x
        outScreenRect[1] = rect.origin.y
        outScreenRect[2] = rect.size.width
        outScreenRect[3] = rect.size.height
        fields |= FrameInfoFieldBits.screenRect
    }
    if #available(macOS 14.2, *),
       let dict = attachment[SCStreamFrameInfo.presenterOverlayContentRect.rawValue as CFString] as? [String: Any],
       let rect = CGRect(dictionaryRepresentation: dict as CFDictionary) {
        outPresenterOverlayRect[0] = rect.origin.x
        outPresenterOverlayRect[1] = rect.origin.y
        outPresenterOverlayRect[2] = rect.size.width
        outPresenterOverlayRect[3] = rect.size.height
        fields |= FrameInfoFieldBits.presenterOverlayRect
    }

    outFields.pointee = fields
    return fields != 0
}

@_cdecl("cm_sample_buffer_get_presentation_timestamp_value")
public func cm_sample_buffer_get_presentation_timestamp_value(_ sampleBuffer: UnsafeMutableRawPointer) -> Int64 {
    let buffer = Unmanaged<CMSampleBuffer>.fromOpaque(sampleBuffer).takeUnretainedValue()
    let time = CMSampleBufferGetPresentationTimeStamp(buffer)
    return time.value
}

@_cdecl("cm_sample_buffer_get_presentation_timestamp_timescale")
public func cm_sample_buffer_get_presentation_timestamp_timescale(_ sampleBuffer: UnsafeMutableRawPointer) -> Int32 {
    let buffer = Unmanaged<CMSampleBuffer>.fromOpaque(sampleBuffer).takeUnretainedValue()
    let time = CMSampleBufferGetPresentationTimeStamp(buffer)
    return time.timescale
}

@_cdecl("cm_sample_buffer_get_presentation_timestamp_flags")
public func cm_sample_buffer_get_presentation_timestamp_flags(_ sampleBuffer: UnsafeMutableRawPointer) -> UInt32 {
    let buffer = Unmanaged<CMSampleBuffer>.fromOpaque(sampleBuffer).takeUnretainedValue()
    let time = CMSampleBufferGetPresentationTimeStamp(buffer)
    return time.flags.rawValue
}

@_cdecl("cm_sample_buffer_get_presentation_timestamp_epoch")
public func cm_sample_buffer_get_presentation_timestamp_epoch(_ sampleBuffer: UnsafeMutableRawPointer) -> Int64 {
    let buffer = Unmanaged<CMSampleBuffer>.fromOpaque(sampleBuffer).takeUnretainedValue()
    let time = CMSampleBufferGetPresentationTimeStamp(buffer)
    return time.epoch
}

@_cdecl("cm_sample_buffer_get_presentation_timestamp")
public func cm_sample_buffer_get_presentation_timestamp(_ sampleBuffer: UnsafeMutableRawPointer, _ outValue: UnsafeMutablePointer<Int64>, _ outTimescale: UnsafeMutablePointer<Int32>, _ outFlags: UnsafeMutablePointer<UInt32>, _ outEpoch: UnsafeMutablePointer<Int64>) {
    let buffer = Unmanaged<CMSampleBuffer>.fromOpaque(sampleBuffer).takeUnretainedValue()
    let time = CMSampleBufferGetPresentationTimeStamp(buffer)
    outValue.pointee = time.value
    outTimescale.pointee = time.timescale
    outFlags.pointee = time.flags.rawValue
    outEpoch.pointee = time.epoch
}

@_cdecl("cm_sample_buffer_get_decode_timestamp")
public func cm_sample_buffer_get_decode_timestamp(
    _ sampleBuffer: UnsafeMutableRawPointer,
    _ value: UnsafeMutablePointer<Int64>,
    _ timescale: UnsafeMutablePointer<Int32>,
    _ flags: UnsafeMutablePointer<UInt32>,
    _ epoch: UnsafeMutablePointer<Int64>
) {
    let buffer = Unmanaged<CMSampleBuffer>.fromOpaque(sampleBuffer).takeUnretainedValue()
    let time = CMSampleBufferGetDecodeTimeStamp(buffer)
    value.pointee = time.value
    timescale.pointee = time.timescale
    flags.pointee = time.flags.rawValue
    epoch.pointee = time.epoch
}

@_cdecl("cm_sample_buffer_get_output_presentation_timestamp")
public func cm_sample_buffer_get_output_presentation_timestamp(
    _ sampleBuffer: UnsafeMutableRawPointer,
    _ value: UnsafeMutablePointer<Int64>,
    _ timescale: UnsafeMutablePointer<Int32>,
    _ flags: UnsafeMutablePointer<UInt32>,
    _ epoch: UnsafeMutablePointer<Int64>
) {
    let buffer = Unmanaged<CMSampleBuffer>.fromOpaque(sampleBuffer).takeUnretainedValue()
    let time = CMSampleBufferGetOutputPresentationTimeStamp(buffer)
    value.pointee = time.value
    timescale.pointee = time.timescale
    flags.pointee = time.flags.rawValue
    epoch.pointee = time.epoch
}

@_cdecl("cm_sample_buffer_set_output_presentation_timestamp")
public func cm_sample_buffer_set_output_presentation_timestamp(
    _ sampleBuffer: UnsafeMutableRawPointer,
    _ value: Int64,
    _ timescale: Int32,
    _ flags: UInt32,
    _ epoch: Int64
) -> Int32 {
    let buffer = Unmanaged<CMSampleBuffer>.fromOpaque(sampleBuffer).takeUnretainedValue()
    let time = CMTime(value: CMTimeValue(value), timescale: timescale, flags: CMTimeFlags(rawValue: flags), epoch: epoch)
    return CMSampleBufferSetOutputPresentationTimeStamp(buffer, newValue: time)
}

@_cdecl("cm_sample_buffer_get_duration_value")
public func cm_sample_buffer_get_duration_value(_ sampleBuffer: UnsafeMutableRawPointer) -> Int64 {
    let buffer = Unmanaged<CMSampleBuffer>.fromOpaque(sampleBuffer).takeUnretainedValue()
    let duration = CMSampleBufferGetDuration(buffer)
    return duration.value
}

@_cdecl("cm_sample_buffer_get_duration_timescale")
public func cm_sample_buffer_get_duration_timescale(_ sampleBuffer: UnsafeMutableRawPointer) -> Int32 {
    let buffer = Unmanaged<CMSampleBuffer>.fromOpaque(sampleBuffer).takeUnretainedValue()
    let duration = CMSampleBufferGetDuration(buffer)
    return duration.timescale
}

@_cdecl("cm_sample_buffer_get_duration_flags")
public func cm_sample_buffer_get_duration_flags(_ sampleBuffer: UnsafeMutableRawPointer) -> UInt32 {
    let buffer = Unmanaged<CMSampleBuffer>.fromOpaque(sampleBuffer).takeUnretainedValue()
    let duration = CMSampleBufferGetDuration(buffer)
    return duration.flags.rawValue
}

@_cdecl("cm_sample_buffer_get_duration_epoch")
public func cm_sample_buffer_get_duration_epoch(_ sampleBuffer: UnsafeMutableRawPointer) -> Int64 {
    let buffer = Unmanaged<CMSampleBuffer>.fromOpaque(sampleBuffer).takeUnretainedValue()
    let duration = CMSampleBufferGetDuration(buffer)
    return duration.epoch
}

@_cdecl("cm_sample_buffer_get_duration")
public func cm_sample_buffer_get_duration(_ sampleBuffer: UnsafeMutableRawPointer, _ outValue: UnsafeMutablePointer<Int64>, _ outTimescale: UnsafeMutablePointer<Int32>, _ outFlags: UnsafeMutablePointer<UInt32>, _ outEpoch: UnsafeMutablePointer<Int64>) {
    let buffer = Unmanaged<CMSampleBuffer>.fromOpaque(sampleBuffer).takeUnretainedValue()
    let duration = CMSampleBufferGetDuration(buffer)
    outValue.pointee = duration.value
    outTimescale.pointee = duration.timescale
    outFlags.pointee = duration.flags.rawValue
    outEpoch.pointee = duration.epoch
}

@_cdecl("cm_sample_buffer_release")
public func cm_sample_buffer_release(_ sampleBuffer: UnsafeMutableRawPointer) {
    Unmanaged<CMSampleBuffer>.fromOpaque(sampleBuffer).release()
}

@_cdecl("cm_sample_buffer_retain")
public func cm_sample_buffer_retain(_ sampleBuffer: UnsafeMutableRawPointer) {
    _ = Unmanaged<CMSampleBuffer>.fromOpaque(sampleBuffer).retain()
}

@_cdecl("cm_sample_buffer_is_valid")
public func cm_sample_buffer_is_valid(_ sampleBuffer: UnsafeMutableRawPointer) -> Bool {
    let buffer = Unmanaged<CMSampleBuffer>.fromOpaque(sampleBuffer).takeUnretainedValue()
    return CMSampleBufferIsValid(buffer)
}

@_cdecl("cm_sample_buffer_get_num_samples")
public func cm_sample_buffer_get_num_samples(_ sampleBuffer: UnsafeMutableRawPointer) -> Int {
    let buffer = Unmanaged<CMSampleBuffer>.fromOpaque(sampleBuffer).takeUnretainedValue()
    return CMSampleBufferGetNumSamples(buffer)
}

@_cdecl("cm_sample_buffer_get_sample_size")
public func cm_sample_buffer_get_sample_size(_ sampleBuffer: UnsafeMutableRawPointer, _ sampleIndex: Int) -> Int {
    let buffer = Unmanaged<CMSampleBuffer>.fromOpaque(sampleBuffer).takeUnretainedValue()
    return CMSampleBufferGetSampleSize(buffer, at: sampleIndex)
}

@_cdecl("cm_sample_buffer_get_total_sample_size")
public func cm_sample_buffer_get_total_sample_size(_ sampleBuffer: UnsafeMutableRawPointer) -> Int {
    let buffer = Unmanaged<CMSampleBuffer>.fromOpaque(sampleBuffer).takeUnretainedValue()
    return CMSampleBufferGetTotalSampleSize(buffer)
}

@_cdecl("cm_sample_buffer_is_ready_for_data_access")
public func cm_sample_buffer_is_ready_for_data_access(_ sampleBuffer: UnsafeMutableRawPointer) -> Bool {
    let buffer = Unmanaged<CMSampleBuffer>.fromOpaque(sampleBuffer).takeUnretainedValue()
    return CMSampleBufferDataIsReady(buffer)
}

@_cdecl("cm_sample_buffer_make_data_ready")
public func cm_sample_buffer_make_data_ready(_ sampleBuffer: UnsafeMutableRawPointer) -> Int32 {
    let buffer = Unmanaged<CMSampleBuffer>.fromOpaque(sampleBuffer).takeUnretainedValue()
    return CMSampleBufferMakeDataReady(buffer)
}

// MARK: - Audio Buffer List Bridge

@_cdecl("cm_sample_buffer_get_audio_buffer_list_num_buffers")
public func cm_sample_buffer_get_audio_buffer_list_num_buffers(_ sampleBuffer: UnsafeMutableRawPointer) -> UInt32 {
    let buffer = Unmanaged<CMSampleBuffer>.fromOpaque(sampleBuffer).takeUnretainedValue()

    var blockBuffer: CMBlockBuffer?
    var audioBufferList = AudioBufferList()

    let status = CMSampleBufferGetAudioBufferListWithRetainedBlockBuffer(
        buffer,
        bufferListSizeNeededOut: nil,
        bufferListOut: &audioBufferList,
        bufferListSize: MemoryLayout<AudioBufferList>.size,
        blockBufferAllocator: nil,
        blockBufferMemoryAllocator: nil,
        flags: 0,
        blockBufferOut: &blockBuffer
    )

    return status == noErr ? audioBufferList.mNumberBuffers : 0
}

@_cdecl("cm_sample_buffer_get_audio_buffer_list")
public func cm_sample_buffer_get_audio_buffer_list(_ sampleBuffer: UnsafeMutableRawPointer, _ outNumBuffers: UnsafeMutablePointer<UInt32>, _ outBuffersPtr: UnsafeMutablePointer<UnsafeMutableRawPointer?>, _ outBuffersLen: UnsafeMutablePointer<UInt>, _ outBlockBuffer: UnsafeMutablePointer<UnsafeMutableRawPointer?>) {
    let buffer = Unmanaged<CMSampleBuffer>.fromOpaque(sampleBuffer).takeUnretainedValue()

    // First, query the required buffer size
    var bufferListSizeNeeded = 0
    var status = CMSampleBufferGetAudioBufferListWithRetainedBlockBuffer(
        buffer,
        bufferListSizeNeededOut: &bufferListSizeNeeded,
        bufferListOut: nil,
        bufferListSize: 0,
        blockBufferAllocator: nil,
        blockBufferMemoryAllocator: nil,
        flags: 0,
        blockBufferOut: nil
    )

    guard bufferListSizeNeeded > 0 else {
        outNumBuffers.pointee = 0
        outBuffersPtr.pointee = nil
        outBuffersLen.pointee = 0
        outBlockBuffer.pointee = nil
        return
    }

    // Allocate buffer of the required size
    let audioBufferListPtr = UnsafeMutablePointer<AudioBufferList>.allocate(capacity: bufferListSizeNeeded / MemoryLayout<AudioBufferList>.stride + 1)
    defer { audioBufferListPtr.deallocate() }

    var blockBuffer: CMBlockBuffer?
    status = CMSampleBufferGetAudioBufferListWithRetainedBlockBuffer(
        buffer,
        bufferListSizeNeededOut: nil,
        bufferListOut: audioBufferListPtr,
        bufferListSize: bufferListSizeNeeded,
        blockBufferAllocator: nil,
        blockBufferMemoryAllocator: nil,
        flags: 0,
        blockBufferOut: &blockBuffer
    )

    guard status == noErr, let blockBuffer else {
        outNumBuffers.pointee = 0
        outBuffersPtr.pointee = nil
        outBuffersLen.pointee = 0
        outBlockBuffer.pointee = nil
        return
    }

    let numBuffers = Int(audioBufferListPtr.pointee.mNumberBuffers)
    guard numBuffers > 0 else {
        outNumBuffers.pointee = 0
        outBuffersPtr.pointee = nil
        outBuffersLen.pointee = 0
        outBlockBuffer.pointee = nil
        return
    }

    let buffers = UnsafeMutablePointer<AudioBufferBridge>.allocate(capacity: numBuffers)

    withUnsafePointer(to: &audioBufferListPtr.pointee.mBuffers) { buffersPtr in
        let bufferArray = UnsafeBufferPointer(start: buffersPtr, count: numBuffers)
        for (index, audioBuffer) in bufferArray.enumerated() {
            buffers[index] = AudioBufferBridge(
                number_channels: audioBuffer.mNumberChannels,
                data_bytes_size: audioBuffer.mDataByteSize,
                data_ptr: audioBuffer.mData
            )
        }
    }

    outNumBuffers.pointee = UInt32(numBuffers)
    outBuffersPtr.pointee = UnsafeMutableRawPointer(buffers)
    outBuffersLen.pointee = UInt(numBuffers)
    // Retain the block buffer to keep data alive, caller must release
    outBlockBuffer.pointee = Unmanaged.passRetained(blockBuffer).toOpaque()
}

@_cdecl("cm_block_buffer_release")
public func cm_block_buffer_release(_ blockBuffer: UnsafeMutableRawPointer) {
    _ = Unmanaged<CMBlockBuffer>.fromOpaque(blockBuffer).takeRetainedValue()
}

@_cdecl("cm_block_buffer_retain")
public func cm_block_buffer_retain(_ blockBuffer: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer {
    let buffer = Unmanaged<CMBlockBuffer>.fromOpaque(blockBuffer).takeUnretainedValue()
    return Unmanaged.passRetained(buffer).toOpaque()
}

@_cdecl("cm_block_buffer_get_data_length")
public func cm_block_buffer_get_data_length(_ blockBuffer: UnsafeMutableRawPointer) -> Int {
    let buffer = Unmanaged<CMBlockBuffer>.fromOpaque(blockBuffer).takeUnretainedValue()
    return CMBlockBufferGetDataLength(buffer)
}

@_cdecl("cm_block_buffer_is_empty")
public func cm_block_buffer_is_empty(_ blockBuffer: UnsafeMutableRawPointer) -> Bool {
    let buffer = Unmanaged<CMBlockBuffer>.fromOpaque(blockBuffer).takeUnretainedValue()
    return CMBlockBufferIsEmpty(buffer)
}

@_cdecl("cm_block_buffer_is_range_contiguous")
public func cm_block_buffer_is_range_contiguous(_ blockBuffer: UnsafeMutableRawPointer, _ offset: Int, _ length: Int) -> Bool {
    let buffer = Unmanaged<CMBlockBuffer>.fromOpaque(blockBuffer).takeUnretainedValue()
    return CMBlockBufferIsRangeContiguous(buffer, atOffset: offset, length: length)
}

@_cdecl("cm_block_buffer_get_data_pointer")
public func cm_block_buffer_get_data_pointer(
    _ blockBuffer: UnsafeMutableRawPointer,
    _ offset: Int,
    _ outLengthAtOffset: UnsafeMutablePointer<Int>,
    _ outTotalLength: UnsafeMutablePointer<Int>,
    _ outDataPointer: UnsafeMutablePointer<UnsafeMutableRawPointer?>
) -> Int32 {
    let buffer = Unmanaged<CMBlockBuffer>.fromOpaque(blockBuffer).takeUnretainedValue()
    var lengthAtOffset: Int = 0
    var totalLength: Int = 0
    var dataPointer: UnsafeMutablePointer<CChar>?
    
    let status = CMBlockBufferGetDataPointer(
        buffer,
        atOffset: offset,
        lengthAtOffsetOut: &lengthAtOffset,
        totalLengthOut: &totalLength,
        dataPointerOut: &dataPointer
    )
    
    outLengthAtOffset.pointee = lengthAtOffset
    outTotalLength.pointee = totalLength
    outDataPointer.pointee = dataPointer.map { UnsafeMutableRawPointer($0) }
    
    return status
}

@_cdecl("cm_block_buffer_copy_data_bytes")
public func cm_block_buffer_copy_data_bytes(
    _ blockBuffer: UnsafeMutableRawPointer,
    _ offsetToData: Int,
    _ dataLength: Int,
    _ destination: UnsafeMutableRawPointer
) -> Int32 {
    let buffer = Unmanaged<CMBlockBuffer>.fromOpaque(blockBuffer).takeUnretainedValue()
    return CMBlockBufferCopyDataBytes(
        buffer,
        atOffset: offsetToData,
        dataLength: dataLength,
        destination: destination
    )
}

@_cdecl("cm_sample_buffer_get_data_buffer")
public func cm_sample_buffer_get_data_buffer(_ sampleBuffer: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer? {
    let buffer = Unmanaged<CMSampleBuffer>.fromOpaque(sampleBuffer).takeUnretainedValue()
    guard let dataBuffer = CMSampleBufferGetDataBuffer(buffer) else {
        return nil
    }
    return Unmanaged.passRetained(dataBuffer).toOpaque()
}

// MARK: - CMFormatDescription APIs

@_cdecl("cm_sample_buffer_get_format_description")
public func cm_sample_buffer_get_format_description(_ sampleBuffer: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer? {
    let buffer = Unmanaged<CMSampleBuffer>.fromOpaque(sampleBuffer).takeUnretainedValue()
    guard let formatDesc = CMSampleBufferGetFormatDescription(buffer) else {
        return nil
    }
    return Unmanaged.passRetained(formatDesc).toOpaque()
}

@_cdecl("cm_sample_buffer_get_sample_timing_info")
public func cm_sample_buffer_get_sample_timing_info(
    _ sampleBuffer: UnsafeMutableRawPointer,
    _ sampleIndex: Int,
    _ outDurationValue: UnsafeMutablePointer<Int64>,
    _ outDurationTimescale: UnsafeMutablePointer<Int32>,
    _ outDurationFlags: UnsafeMutablePointer<UInt32>,
    _ outDurationEpoch: UnsafeMutablePointer<Int64>,
    _ outPtsValue: UnsafeMutablePointer<Int64>,
    _ outPtsTimescale: UnsafeMutablePointer<Int32>,
    _ outPtsFlags: UnsafeMutablePointer<UInt32>,
    _ outPtsEpoch: UnsafeMutablePointer<Int64>,
    _ outDtsValue: UnsafeMutablePointer<Int64>,
    _ outDtsTimescale: UnsafeMutablePointer<Int32>,
    _ outDtsFlags: UnsafeMutablePointer<UInt32>,
    _ outDtsEpoch: UnsafeMutablePointer<Int64>
) -> Int32 {
    let buffer = Unmanaged<CMSampleBuffer>.fromOpaque(sampleBuffer).takeUnretainedValue()
    var timingInfo = CMSampleTimingInfo()
    let status = CMSampleBufferGetSampleTimingInfo(buffer, at: sampleIndex, timingInfoOut: &timingInfo)

    if status == noErr {
        outDurationValue.pointee = timingInfo.duration.value
        outDurationTimescale.pointee = timingInfo.duration.timescale
        outDurationFlags.pointee = timingInfo.duration.flags.rawValue
        outDurationEpoch.pointee = timingInfo.duration.epoch

        outPtsValue.pointee = timingInfo.presentationTimeStamp.value
        outPtsTimescale.pointee = timingInfo.presentationTimeStamp.timescale
        outPtsFlags.pointee = timingInfo.presentationTimeStamp.flags.rawValue
        outPtsEpoch.pointee = timingInfo.presentationTimeStamp.epoch

        outDtsValue.pointee = timingInfo.decodeTimeStamp.value
        outDtsTimescale.pointee = timingInfo.decodeTimeStamp.timescale
        outDtsFlags.pointee = timingInfo.decodeTimeStamp.flags.rawValue
        outDtsEpoch.pointee = timingInfo.decodeTimeStamp.epoch
    }

    return status
}

@_cdecl("cm_sample_buffer_invalidate")
public func cm_sample_buffer_invalidate(_ sampleBuffer: UnsafeMutableRawPointer) -> Int32 {
    let buffer = Unmanaged<CMSampleBuffer>.fromOpaque(sampleBuffer).takeUnretainedValue()
    CMSampleBufferInvalidate(buffer)
    return 0
}

@_cdecl("cm_sample_buffer_create_copy_with_new_timing")
public func cm_sample_buffer_create_copy_with_new_timing(
    _ sampleBuffer: UnsafeMutableRawPointer,
    _ numTimingInfos: Int,
    _ timingInfoArray: UnsafeRawPointer,
    _ sampleBufferOut: UnsafeMutablePointer<UnsafeMutableRawPointer?>
) -> Int32 {
    let buffer = Unmanaged<CMSampleBuffer>.fromOpaque(sampleBuffer).takeUnretainedValue()
    let timingInfos = timingInfoArray.bindMemory(to: CMSampleTimingInfo.self, capacity: numTimingInfos)
    let timingArray = Array(UnsafeBufferPointer(start: timingInfos, count: numTimingInfos))

    var newBuffer: CMSampleBuffer?
    let status = CMSampleBufferCreateCopyWithNewTiming(
        allocator: kCFAllocatorDefault,
        sampleBuffer: buffer,
        sampleTimingEntryCount: numTimingInfos,
        sampleTimingArray: timingArray,
        sampleBufferOut: &newBuffer
    )

    if status == noErr, let newBuf = newBuffer {
        sampleBufferOut.pointee = Unmanaged.passRetained(newBuf).toOpaque()
    } else {
        sampleBufferOut.pointee = nil
    }

    return status
}

@_cdecl("cm_sample_buffer_copy_pcm_data_into_audio_buffer_list")
public func cm_sample_buffer_copy_pcm_data_into_audio_buffer_list(
    _ sampleBuffer: UnsafeMutableRawPointer,
    _ frameOffset: Int32,
    _ numFrames: Int32,
    _ bufferList: UnsafeMutableRawPointer
) -> Int32 {
    let buffer = Unmanaged<CMSampleBuffer>.fromOpaque(sampleBuffer).takeUnretainedValue()
    let audioBufferList = bufferList.bindMemory(to: AudioBufferList.self, capacity: 1)

    let status = CMSampleBufferCopyPCMDataIntoAudioBufferList(
        buffer,
        at: frameOffset,
        frameCount: numFrames,
        into: audioBufferList
    )

    return status
}

@_cdecl("cm_format_description_get_media_type")
public func cm_format_description_get_media_type(_ formatDescription: UnsafeMutableRawPointer) -> UInt32 {
    let desc = Unmanaged<CMFormatDescription>.fromOpaque(formatDescription).takeUnretainedValue()
    return CMFormatDescriptionGetMediaType(desc)
}

@_cdecl("cm_format_description_get_media_subtype")
public func cm_format_description_get_media_subtype(_ formatDescription: UnsafeMutableRawPointer) -> UInt32 {
    let desc = Unmanaged<CMFormatDescription>.fromOpaque(formatDescription).takeUnretainedValue()
    return CMFormatDescriptionGetMediaSubType(desc)
}

@_cdecl("cm_format_description_get_extensions")
public func cm_format_description_get_extensions(_ formatDescription: UnsafeMutableRawPointer) -> UnsafeRawPointer? {
    let desc = Unmanaged<CMFormatDescription>.fromOpaque(formatDescription).takeUnretainedValue()
    guard let extensions = CMFormatDescriptionGetExtensions(desc) else {
        return nil
    }
    return UnsafeRawPointer(Unmanaged.passUnretained(extensions).toOpaque())
}

@_cdecl("cm_format_description_retain")
public func cm_format_description_retain(_ formatDescription: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer {
    let desc = Unmanaged<CMFormatDescription>.fromOpaque(formatDescription).takeUnretainedValue()
    return Unmanaged.passRetained(desc).toOpaque()
}

@_cdecl("cm_format_description_release")
public func cm_format_description_release(_ formatDescription: UnsafeMutableRawPointer) {
    Unmanaged<CMFormatDescription>.fromOpaque(formatDescription).release()
}

@_cdecl("cm_format_description_get_audio_sample_rate")
public func cm_format_description_get_audio_sample_rate(_ formatDescription: UnsafeMutableRawPointer) -> Double {
    let desc = Unmanaged<CMFormatDescription>.fromOpaque(formatDescription).takeUnretainedValue()
    guard let asbd = CMAudioFormatDescriptionGetStreamBasicDescription(desc) else {
        return 0.0
    }
    return asbd.pointee.mSampleRate
}

@_cdecl("cm_format_description_get_audio_channel_count")
public func cm_format_description_get_audio_channel_count(_ formatDescription: UnsafeMutableRawPointer) -> UInt32 {
    let desc = Unmanaged<CMFormatDescription>.fromOpaque(formatDescription).takeUnretainedValue()
    guard let asbd = CMAudioFormatDescriptionGetStreamBasicDescription(desc) else {
        return 0
    }
    return asbd.pointee.mChannelsPerFrame
}

@_cdecl("cm_format_description_get_audio_bits_per_channel")
public func cm_format_description_get_audio_bits_per_channel(_ formatDescription: UnsafeMutableRawPointer) -> UInt32 {
    let desc = Unmanaged<CMFormatDescription>.fromOpaque(formatDescription).takeUnretainedValue()
    guard let asbd = CMAudioFormatDescriptionGetStreamBasicDescription(desc) else {
        return 0
    }
    return asbd.pointee.mBitsPerChannel
}

@_cdecl("cm_format_description_get_audio_bytes_per_frame")
public func cm_format_description_get_audio_bytes_per_frame(_ formatDescription: UnsafeMutableRawPointer) -> UInt32 {
    let desc = Unmanaged<CMFormatDescription>.fromOpaque(formatDescription).takeUnretainedValue()
    guard let asbd = CMAudioFormatDescriptionGetStreamBasicDescription(desc) else {
        return 0
    }
    return asbd.pointee.mBytesPerFrame
}

@_cdecl("cm_format_description_get_audio_format_flags")
public func cm_format_description_get_audio_format_flags(_ formatDescription: UnsafeMutableRawPointer) -> UInt32 {
    let desc = Unmanaged<CMFormatDescription>.fromOpaque(formatDescription).takeUnretainedValue()
    guard let asbd = CMAudioFormatDescriptionGetStreamBasicDescription(desc) else {
        return 0
    }
    return asbd.pointee.mFormatFlags
}

// MARK: - CMSampleBuffer Creation

@_cdecl("cm_sample_buffer_create_for_image_buffer")
public func cm_sample_buffer_create_for_image_buffer(
    _ imageBuffer: UnsafeMutableRawPointer,
    _ presentationTimeValue: Int64,
    _ presentationTimeScale: Int32,
    _ durationValue: Int64,
    _ durationScale: Int32,
    _ sampleBufferOut: UnsafeMutablePointer<UnsafeMutableRawPointer?>
) -> Int32 {
    let pixelBuffer = Unmanaged<CVPixelBuffer>.fromOpaque(imageBuffer).takeUnretainedValue()

    var sampleBuffer: CMSampleBuffer?
    var timingInfo = CMSampleTimingInfo(
        duration: CMTime(value: CMTimeValue(durationValue), timescale: durationScale, flags: .valid, epoch: 0),
        presentationTimeStamp: CMTime(value: CMTimeValue(presentationTimeValue), timescale: presentationTimeScale, flags: .valid, epoch: 0),
        decodeTimeStamp: .invalid
    )

    var formatDescription: CMFormatDescription?
    let descStatus = CMVideoFormatDescriptionCreateForImageBuffer(
        allocator: kCFAllocatorDefault,
        imageBuffer: pixelBuffer,
        formatDescriptionOut: &formatDescription
    )

    guard descStatus == noErr, let format = formatDescription else {
        sampleBufferOut.pointee = nil
        return descStatus
    }

    let status = CMSampleBufferCreateReadyWithImageBuffer(
        allocator: kCFAllocatorDefault,
        imageBuffer: pixelBuffer,
        formatDescription: format,
        sampleTiming: &timingInfo,
        sampleBufferOut: &sampleBuffer
    )

    if status == noErr, let buffer = sampleBuffer {
        sampleBufferOut.pointee = Unmanaged.passRetained(buffer).toOpaque()
    } else {
        sampleBufferOut.pointee = nil
    }

    return status
}

// MARK: - Hash Functions

@_cdecl("cm_sample_buffer_hash")
public func cm_sample_buffer_hash(_ sampleBuffer: UnsafeMutableRawPointer) -> Int {
    let buffer = Unmanaged<CMSampleBuffer>.fromOpaque(sampleBuffer).takeUnretainedValue()
    return buffer.hashValue
}

@_cdecl("cm_block_buffer_hash")
public func cm_block_buffer_hash(_ blockBuffer: UnsafeMutableRawPointer) -> Int {
    let buffer = Unmanaged<CMBlockBuffer>.fromOpaque(blockBuffer).takeUnretainedValue()
    return buffer.hashValue
}

@_cdecl("cm_format_description_hash")
public func cm_format_description_hash(_ formatDescription: UnsafeMutableRawPointer) -> Int {
    let desc = Unmanaged<CMFormatDescription>.fromOpaque(formatDescription).takeUnretainedValue()
    return desc.hashValue
}

// MARK: - CMBlockBuffer Creation (for testing)

/// Create a CMBlockBuffer with the given data for testing purposes
@_cdecl("cm_block_buffer_create_with_data")
public func cm_block_buffer_create_with_data(
    _ data: UnsafeRawPointer,
    _ dataLength: Int,
    _ blockBufferOut: UnsafeMutablePointer<UnsafeMutableRawPointer?>
) -> Int32 {
    var blockBuffer: CMBlockBuffer?
    
    // Create a block buffer with memory block
    let status = CMBlockBufferCreateWithMemoryBlock(
        allocator: kCFAllocatorDefault,
        memoryBlock: nil,  // Let CM allocate memory
        blockLength: dataLength,
        blockAllocator: kCFAllocatorDefault,
        customBlockSource: nil,
        offsetToData: 0,
        dataLength: dataLength,
        flags: 0,
        blockBufferOut: &blockBuffer
    )
    
    guard status == noErr, let buffer = blockBuffer else {
        blockBufferOut.pointee = nil
        return status
    }
    
    // Copy data into the block buffer
    let copyStatus = CMBlockBufferReplaceDataBytes(
        with: data,
        blockBuffer: buffer,
        offsetIntoDestination: 0,
        dataLength: dataLength
    )
    
    guard copyStatus == noErr else {
        blockBufferOut.pointee = nil
        return copyStatus
    }
    
    blockBufferOut.pointee = Unmanaged.passRetained(buffer).toOpaque()
    return noErr
}

/// Create an empty CMBlockBuffer for testing
@_cdecl("cm_block_buffer_create_empty")
public func cm_block_buffer_create_empty(
    _ blockBufferOut: UnsafeMutablePointer<UnsafeMutableRawPointer?>
) -> Int32 {
    var blockBuffer: CMBlockBuffer?
    
    let status = CMBlockBufferCreateEmpty(
        allocator: kCFAllocatorDefault,
        capacity: 0,
        flags: 0,
        blockBufferOut: &blockBuffer
    )
    
    if status == noErr, let buffer = blockBuffer {
        blockBufferOut.pointee = Unmanaged.passRetained(buffer).toOpaque()
    } else {
        blockBufferOut.pointee = nil
    }
    
    return status
}