Skip to content

Commit 06d1618

Browse files
Copiloteerimoq
andcommitted
Use safer nested withUnsafeBytes pattern for H.264 format description creation
Co-authored-by: eerimoq <176810+eerimoq@users.noreply.github.com>
1 parent d3ee0c1 commit 06d1618

File tree

1 file changed

+22
-30
lines changed

1 file changed

+22
-30
lines changed

Moblin/Media/HaishinKit/Whip/WhipServerClient.swift

Lines changed: 22 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -352,17 +352,29 @@ final class WhipServerClient {
352352
guard let sps, let pps else {
353353
return
354354
}
355-
let parameterSets: [Data] = [sps, pps]
356355
var formatDescription: CMFormatDescription?
357-
parameterSets.withUnsafeBufferPointers { pointers, sizes in
358-
CMVideoFormatDescriptionCreateFromH264ParameterSets(
359-
allocator: kCFAllocatorDefault,
360-
parameterSetCount: pointers.count,
361-
parameterSetPointers: pointers.baseAddress!,
362-
parameterSetSizes: sizes.baseAddress!,
363-
nalUnitHeaderLength: 4,
364-
formatDescriptionOut: &formatDescription
365-
)
356+
sps.withUnsafeBytes { spsBuffer in
357+
guard let spsBaseAddress = spsBuffer.baseAddress else {
358+
return
359+
}
360+
pps.withUnsafeBytes { ppsBuffer in
361+
guard let ppsBaseAddress = ppsBuffer.baseAddress else {
362+
return
363+
}
364+
let pointers = [
365+
spsBaseAddress.assumingMemoryBound(to: UInt8.self),
366+
ppsBaseAddress.assumingMemoryBound(to: UInt8.self),
367+
]
368+
let sizes = [spsBuffer.count, ppsBuffer.count]
369+
CMVideoFormatDescriptionCreateFromH264ParameterSets(
370+
allocator: kCFAllocatorDefault,
371+
parameterSetCount: pointers.count,
372+
parameterSetPointers: pointers,
373+
parameterSetSizes: sizes,
374+
nalUnitHeaderLength: 4,
375+
formatDescriptionOut: &formatDescription
376+
)
377+
}
366378
}
367379
if let formatDescription {
368380
self.videoFormatDescription = formatDescription
@@ -517,23 +529,3 @@ private func checkWhipServerOk(_ result: Int32) throws {
517529
throw "Error \(result)"
518530
}
519531
}
520-
521-
private extension Array where Element == Data {
522-
func withUnsafeBufferPointers<R>(
523-
_ body: (UnsafeBufferPointer<UnsafePointer<UInt8>>, UnsafeBufferPointer<Int>) -> R
524-
) -> R {
525-
let pointers = UnsafeMutableBufferPointer<UnsafePointer<UInt8>>.allocate(capacity: count)
526-
let sizes = UnsafeMutableBufferPointer<Int>.allocate(capacity: count)
527-
defer {
528-
pointers.deallocate()
529-
sizes.deallocate()
530-
}
531-
for (index, data) in enumerated() {
532-
data.withUnsafeBytes { rawBuffer in
533-
pointers[index] = rawBuffer.bindMemory(to: UInt8.self).baseAddress!
534-
sizes[index] = rawBuffer.count
535-
}
536-
}
537-
return body(UnsafeBufferPointer(pointers), UnsafeBufferPointer(sizes))
538-
}
539-
}

0 commit comments

Comments
 (0)