| 1 | #import <Accelerate/Accelerate.h> |
| 2 | #import <AVFoundation/AVFoundation.h> |
| 3 | #import <CoreFoundation/CoreFoundation.h> |
| 4 | #import <CoreMedia/CoreMedia.h> |
| 5 | #import <CoreVideo/CoreVideo.h> |
| 6 | #import <Foundation/Foundation.h> |
| 7 | #include <math.h> |
| 8 | #include <stdint.h> |
| 9 | #include <stddef.h> |
| 10 | #include <string.h> |
| 11 | #if defined(__aarch64__) |
| 12 | #include <arm_neon.h> |
| 13 | #endif |
| 14 | |
| 15 | #pragma clang diagnostic push |
| 16 | #pragma clang diagnostic ignored "-Wdeprecated-declarations" |
| 17 | |
| 18 | @interface AvVideoDecoderObj : NSObject |
| 19 | @property(nonatomic, strong) AVURLAsset *asset; |
| 20 | @property(nonatomic, strong) AVAssetTrack *track; |
| 21 | @property(nonatomic, strong) AVAssetReader *reader; |
| 22 | @property(nonatomic, strong) AVAssetReaderTrackOutput *output; |
| 23 | @property(nonatomic, assign) uint32_t width; |
| 24 | @property(nonatomic, assign) uint32_t height; |
| 25 | @property(nonatomic, assign) uint32_t rawWidth; |
| 26 | @property(nonatomic, assign) uint32_t rawHeight; |
| 27 | @property(nonatomic, assign) int rotation; // 0, 90, 180, 270 clockwise |
| 28 | @property(nonatomic, assign) BOOL useNv12; |
| 29 | @property(nonatomic, assign) BOOL preferFullRange; |
| 30 | @property(nonatomic, assign) uint32_t defaultMatrix; // 0=BT.709, 1=BT.601, 2=BT.2020 |
| 31 | @property(nonatomic, assign) double fps; |
| 32 | @property(nonatomic, assign) int64_t nbFrames; |
| 33 | @property(nonatomic, assign) double trackStartSec; |
| 34 | @property(nonatomic, assign) double durSec; |
| 35 | @property(nonatomic, assign) int64_t lastFrameIdx; |
| 36 | @property(nonatomic, strong) NSMutableData *lastFrameRgba; |
| 37 | @property(nonatomic, strong) NSMutableData *lastFrameY; |
| 38 | @property(nonatomic, strong) NSMutableData *lastFrameUv; |
| 39 | @property(nonatomic, assign) uint32_t lastFrameMatrix; |
| 40 | @property(nonatomic, assign) uint32_t lastFrameFullRange; |
| 41 | @property(nonatomic, assign) BOOL hasLastFrame; |
| 42 | @property(nonatomic, assign) BOOL lastFrameIsEof; |
| 43 | @end |
| 44 | |
| 45 | @implementation AvVideoDecoderObj |
| 46 | |
| 47 | - (void)closeReader { |
| 48 | if (self.reader) { |
| 49 | [self.reader cancelReading]; |
| 50 | self.reader = nil; |
| 51 | self.output = nil; |
| 52 | } |
| 53 | self.lastFrameIdx = -1; |
| 54 | } |
| 55 | |
| 56 | - (BOOL)openReaderAtSeconds:(double)startSec { |
| 57 | [self closeReader]; |
| 58 | NSError *err = nil; |
| 59 | AVAssetReader *r = [[AVAssetReader alloc] initWithAsset:self.asset error:&err]; |
| 60 | if (!r || err) { |
| 61 | return NO; |
| 62 | } |
| 63 | OSType pixFmt = kCVPixelFormatType_32BGRA; |
| 64 | if (self.useNv12) { |
| 65 | pixFmt = self.preferFullRange |
| 66 | ? kCVPixelFormatType_420YpCbCr8BiPlanarFullRange |
| 67 | : kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange; |
| 68 | } |
| 69 | NSDictionary *settings = @{ |
| 70 | (NSString *)kCVPixelBufferPixelFormatTypeKey : @(pixFmt), |
| 71 | }; |
| 72 | AVAssetReaderTrackOutput *out = |
| 73 | [[AVAssetReaderTrackOutput alloc] initWithTrack:self.track outputSettings:settings]; |
| 74 | out.alwaysCopiesSampleData = NO; |
| 75 | if (![r canAddOutput:out]) { |
| 76 | return NO; |
| 77 | } |
| 78 | [r addOutput:out]; |
| 79 | if (startSec > 0.0) { |
| 80 | CMTime startTime = CMTimeMakeWithSeconds(startSec, 60000); |
| 81 | r.timeRange = CMTimeRangeMake(startTime, kCMTimePositiveInfinity); |
| 82 | } |
| 83 | if (![r startReading]) { |
| 84 | return NO; |
| 85 | } |
| 86 | self.reader = r; |
| 87 | self.output = out; |
| 88 | return YES; |
| 89 | } |
| 90 | |
| 91 | - (void)dealloc { |
| 92 | [self closeReader]; |
| 93 | } |
| 94 | |
| 95 | @end |
| 96 | |
| 97 | typedef struct AvVideoDecoder AvVideoDecoder; |
| 98 | |
| 99 | static inline void bgra_to_rgba_pixel(const uint8_t *src, uint8_t *dst) { |
| 100 | dst[0] = src[2]; |
| 101 | dst[1] = src[1]; |
| 102 | dst[2] = src[0]; |
| 103 | dst[3] = src[3]; |
| 104 | } |
| 105 | |
| 106 | #if defined(__aarch64__) |
| 107 | static inline void neon_transpose4x4_bgra_to_rgba( |
| 108 | const uint8_t *r0, |
| 109 | const uint8_t *r1, |
| 110 | const uint8_t *r2, |
| 111 | const uint8_t *r3, |
| 112 | uint8x16_t swizTbl, |
| 113 | uint8_t *d0Out, |
| 114 | uint8_t *d1Out, |
| 115 | uint8_t *d2Out, |
| 116 | uint8_t *d3Out |
| 117 | ) { |
| 118 | uint32x4_t p0 = vreinterpretq_u32_u8(vqtbl1q_u8(vld1q_u8(r0), swizTbl)); |
| 119 | uint32x4_t p1 = vreinterpretq_u32_u8(vqtbl1q_u8(vld1q_u8(r1), swizTbl)); |
| 120 | uint32x4_t p2 = vreinterpretq_u32_u8(vqtbl1q_u8(vld1q_u8(r2), swizTbl)); |
| 121 | uint32x4_t p3 = vreinterpretq_u32_u8(vqtbl1q_u8(vld1q_u8(r3), swizTbl)); |
| 122 | uint32x4_t t0 = vtrn1q_u32(p0, p1); |
| 123 | uint32x4_t t1 = vtrn2q_u32(p0, p1); |
| 124 | uint32x4_t t2 = vtrn1q_u32(p2, p3); |
| 125 | uint32x4_t t3 = vtrn2q_u32(p2, p3); |
| 126 | uint32x4_t d0 = vreinterpretq_u32_u64( |
| 127 | vtrn1q_u64(vreinterpretq_u64_u32(t0), vreinterpretq_u64_u32(t2))); |
| 128 | uint32x4_t d1 = vreinterpretq_u32_u64( |
| 129 | vtrn1q_u64(vreinterpretq_u64_u32(t1), vreinterpretq_u64_u32(t3))); |
| 130 | uint32x4_t d2 = vreinterpretq_u32_u64( |
| 131 | vtrn2q_u64(vreinterpretq_u64_u32(t0), vreinterpretq_u64_u32(t2))); |
| 132 | uint32x4_t d3 = vreinterpretq_u32_u64( |
| 133 | vtrn2q_u64(vreinterpretq_u64_u32(t1), vreinterpretq_u64_u32(t3))); |
| 134 | vst1q_u8(d0Out, vreinterpretq_u8_u32(d0)); |
| 135 | vst1q_u8(d1Out, vreinterpretq_u8_u32(d1)); |
| 136 | vst1q_u8(d2Out, vreinterpretq_u8_u32(d2)); |
| 137 | vst1q_u8(d3Out, vreinterpretq_u8_u32(d3)); |
| 138 | } |
| 139 | #endif |
| 140 | |
| 141 | static int copy_bgra_to_rgba( |
| 142 | CVImageBufferRef imgBuf, |
| 143 | uint32_t outW, |
| 144 | uint32_t outH, |
| 145 | int rotation, |
| 146 | uint8_t *outRgba, |
| 147 | size_t outLen |
| 148 | ) { |
| 149 | if (!imgBuf || !outRgba) { |
| 150 | return 0; |
| 151 | } |
| 152 | size_t required = (size_t)outW * (size_t)outH * 4; |
| 153 | if (outLen < required) { |
| 154 | return 0; |
| 155 | } |
| 156 | |
| 157 | if (CVPixelBufferLockBaseAddress(imgBuf, kCVPixelBufferLock_ReadOnly) != kCVReturnSuccess) { |
| 158 | return 0; |
| 159 | } |
| 160 | |
| 161 | size_t srcW = CVPixelBufferGetWidth(imgBuf); |
| 162 | size_t srcH = CVPixelBufferGetHeight(imgBuf); |
| 163 | size_t bpr = CVPixelBufferGetBytesPerRow(imgBuf); |
| 164 | const uint8_t *base = (const uint8_t *)CVPixelBufferGetBaseAddress(imgBuf); |
| 165 | |
| 166 | int ok = 0; |
| 167 | if (base && srcW > 0 && srcH > 0 && bpr >= srcW * 4) { |
| 168 | const size_t dstBpr = (size_t)outW * 4; |
| 169 | const uint8_t permuteMap[4] = { 2, 1, 0, 3 }; |
| 170 | // Disable internal vImage GCD tiling so parallel decoder threads do not oversubscribe cores. |
| 171 | const vImage_Flags vflags = kvImageDoNotTile; |
| 172 | vImage_Buffer srcBuf = { (void *)base, (vImagePixelCount)srcH, (vImagePixelCount)srcW, bpr }; |
| 173 | vImage_Buffer dstBuf = { (void *)outRgba, (vImagePixelCount)outH, (vImagePixelCount)outW, dstBpr }; |
| 174 | |
| 175 | if (rotation == 0 && srcW == outW && srcH == outH) { |
| 176 | if (vImagePermuteChannels_ARGB8888(&srcBuf, &dstBuf, permuteMap, vflags) == kvImageNoError) { |
| 177 | ok = 1; |
| 178 | } else { |
| 179 | for (size_t y = 0; y < srcH; y++) { |
| 180 | const uint8_t *src = base + y * bpr; |
| 181 | uint8_t *dst = outRgba + y * dstBpr; |
| 182 | for (size_t x = 0; x < srcW; x++) { |
| 183 | bgra_to_rgba_pixel(src + x * 4, dst + x * 4); |
| 184 | } |
| 185 | } |
| 186 | ok = 1; |
| 187 | } |
| 188 | } else if (rotation == 90 && srcH == outW && srcW == outH) { |
| 189 | #if defined(__aarch64__) |
| 190 | const uint8_t swizTblBytes[16] = { 2, 1, 0, 3, 6, 5, 4, 7, 10, 9, 8, 11, 14, 13, 12, 15 }; |
| 191 | uint8x16_t swizTbl = vld1q_u8(swizTblBytes); |
| 192 | const size_t B = 32; |
| 193 | for (size_t by = 0; by < srcH; by += B) { |
| 194 | size_t bh = (by + B <= srcH) ? B : (srcH - by); |
| 195 | for (size_t bx = 0; bx < srcW; bx += B) { |
| 196 | size_t bw = (bx + B <= srcW) ? B : (srcW - bx); |
| 197 | size_t y = 0; |
| 198 | for (; y + 4 <= bh; y += 4) { |
| 199 | size_t sy = by + y; |
| 200 | size_t dxBase = srcH - 1 - (sy + 3); |
| 201 | const uint8_t *r0 = base + (sy + 0) * bpr + bx * 4; |
| 202 | const uint8_t *r1 = base + (sy + 1) * bpr + bx * 4; |
| 203 | const uint8_t *r2 = base + (sy + 2) * bpr + bx * 4; |
| 204 | const uint8_t *r3 = base + (sy + 3) * bpr + bx * 4; |
| 205 | size_t x = 0; |
| 206 | for (; x + 4 <= bw; x += 4) { |
| 207 | uint8_t *dst = outRgba + (bx + x) * dstBpr + dxBase * 4; |
| 208 | neon_transpose4x4_bgra_to_rgba( |
| 209 | r3 + x * 4, r2 + x * 4, r1 + x * 4, r0 + x * 4, |
| 210 | swizTbl, |
| 211 | dst + 0 * dstBpr, dst + 1 * dstBpr, dst + 2 * dstBpr, dst + 3 * dstBpr |
| 212 | ); |
| 213 | } |
| 214 | for (; x < bw; x++) { |
| 215 | size_t dy = bx + x; |
| 216 | for (size_t k = 0; k < 4; k++) { |
| 217 | size_t dx = srcH - 1 - (sy + k); |
| 218 | bgra_to_rgba_pixel( |
| 219 | base + (sy + k) * bpr + (bx + x) * 4, |
| 220 | outRgba + dy * dstBpr + dx * 4 |
| 221 | ); |
| 222 | } |
| 223 | } |
| 224 | } |
| 225 | for (; y < bh; y++) { |
| 226 | size_t sy = by + y; |
| 227 | size_t dx = srcH - 1 - sy; |
| 228 | const uint8_t *src = base + sy * bpr + bx * 4; |
| 229 | for (size_t x = 0; x < bw; x++) { |
| 230 | size_t dy = bx + x; |
| 231 | bgra_to_rgba_pixel(src + x * 4, outRgba + dy * dstBpr + dx * 4); |
| 232 | } |
| 233 | } |
| 234 | } |
| 235 | } |
| 236 | ok = 1; |
| 237 | #else |
| 238 | const Pixel_8888 back = { 0, 0, 0, 0 }; |
| 239 | if (vImageRotate90_ARGB8888(&srcBuf, &dstBuf, kRotate90DegreesClockwise, back, vflags) == kvImageNoError && |
| 240 | vImagePermuteChannels_ARGB8888(&dstBuf, &dstBuf, permuteMap, vflags) == kvImageNoError) { |
| 241 | ok = 1; |
| 242 | } |
| 243 | #endif |
| 244 | } else if (rotation == 180 && srcW == outW && srcH == outH) { |
| 245 | #if defined(__aarch64__) |
| 246 | const uint8_t revSwizBytes[16] = { 14, 13, 12, 15, 10, 9, 8, 11, 6, 5, 4, 7, 2, 1, 0, 3 }; |
| 247 | uint8x16_t revSwiz = vld1q_u8(revSwizBytes); |
| 248 | for (size_t y = 0; y < srcH; y++) { |
| 249 | const uint8_t *src = base + y * bpr; |
| 250 | uint8_t *dstRow = outRgba + (srcH - 1 - y) * dstBpr; |
| 251 | size_t x = 0; |
| 252 | for (; x + 4 <= srcW; x += 4) { |
| 253 | uint8x16_t v = vld1q_u8(src + x * 4); |
| 254 | vst1q_u8(dstRow + (srcW - x - 4) * 4, vqtbl1q_u8(v, revSwiz)); |
| 255 | } |
| 256 | for (; x < srcW; x++) { |
| 257 | bgra_to_rgba_pixel(src + x * 4, dstRow + (srcW - 1 - x) * 4); |
| 258 | } |
| 259 | } |
| 260 | ok = 1; |
| 261 | #else |
| 262 | const Pixel_8888 back = { 0, 0, 0, 0 }; |
| 263 | if (vImageRotate90_ARGB8888(&srcBuf, &dstBuf, kRotate180DegreesClockwise, back, vflags) == kvImageNoError && |
| 264 | vImagePermuteChannels_ARGB8888(&dstBuf, &dstBuf, permuteMap, vflags) == kvImageNoError) { |
| 265 | ok = 1; |
| 266 | } |
| 267 | #endif |
| 268 | } else if (rotation == 270 && srcH == outW && srcW == outH) { |
| 269 | #if defined(__aarch64__) |
| 270 | const uint8_t swizTblBytes[16] = { 2, 1, 0, 3, 6, 5, 4, 7, 10, 9, 8, 11, 14, 13, 12, 15 }; |
| 271 | uint8x16_t swizTbl = vld1q_u8(swizTblBytes); |
| 272 | const size_t B = 32; |
| 273 | for (size_t by = 0; by < srcH; by += B) { |
| 274 | size_t bh = (by + B <= srcH) ? B : (srcH - by); |
| 275 | for (size_t bx = 0; bx < srcW; bx += B) { |
| 276 | size_t bw = (bx + B <= srcW) ? B : (srcW - bx); |
| 277 | size_t y = 0; |
| 278 | for (; y + 4 <= bh; y += 4) { |
| 279 | size_t sy = by + y; |
| 280 | const uint8_t *r0 = base + (sy + 0) * bpr + bx * 4; |
| 281 | const uint8_t *r1 = base + (sy + 1) * bpr + bx * 4; |
| 282 | const uint8_t *r2 = base + (sy + 2) * bpr + bx * 4; |
| 283 | const uint8_t *r3 = base + (sy + 3) * bpr + bx * 4; |
| 284 | size_t x = 0; |
| 285 | for (; x + 4 <= bw; x += 4) { |
| 286 | size_t dyTop = srcW - 1 - (bx + x); |
| 287 | neon_transpose4x4_bgra_to_rgba( |
| 288 | r0 + x * 4, r1 + x * 4, r2 + x * 4, r3 + x * 4, |
| 289 | swizTbl, |
| 290 | outRgba + (dyTop - 0) * dstBpr + sy * 4, |
| 291 | outRgba + (dyTop - 1) * dstBpr + sy * 4, |
| 292 | outRgba + (dyTop - 2) * dstBpr + sy * 4, |
| 293 | outRgba + (dyTop - 3) * dstBpr + sy * 4 |
| 294 | ); |
| 295 | } |
| 296 | for (; x < bw; x++) { |
| 297 | size_t dy = srcW - 1 - (bx + x); |
| 298 | for (size_t k = 0; k < 4; k++) { |
| 299 | size_t dx = sy + k; |
| 300 | bgra_to_rgba_pixel( |
| 301 | base + (sy + k) * bpr + (bx + x) * 4, |
| 302 | outRgba + dy * dstBpr + dx * 4 |
| 303 | ); |
| 304 | } |
| 305 | } |
| 306 | } |
| 307 | for (; y < bh; y++) { |
| 308 | size_t sy = by + y; |
| 309 | size_t dx = sy; |
| 310 | const uint8_t *src = base + sy * bpr + bx * 4; |
| 311 | for (size_t x = 0; x < bw; x++) { |
| 312 | size_t dy = srcW - 1 - (bx + x); |
| 313 | bgra_to_rgba_pixel(src + x * 4, outRgba + dy * dstBpr + dx * 4); |
| 314 | } |
| 315 | } |
| 316 | } |
| 317 | } |
| 318 | ok = 1; |
| 319 | #else |
| 320 | const Pixel_8888 back = { 0, 0, 0, 0 }; |
| 321 | if (vImageRotate90_ARGB8888(&srcBuf, &dstBuf, kRotate270DegreesClockwise, back, vflags) == kvImageNoError && |
| 322 | vImagePermuteChannels_ARGB8888(&dstBuf, &dstBuf, permuteMap, vflags) == kvImageNoError) { |
| 323 | ok = 1; |
| 324 | } |
| 325 | #endif |
| 326 | } |
| 327 | } |
| 328 | |
| 329 | CVPixelBufferUnlockBaseAddress(imgBuf, kCVPixelBufferLock_ReadOnly); |
| 330 | return ok; |
| 331 | } |
| 332 | |
| 333 | static uint32_t matrix_from_cf_string(CFTypeRef matrixRef, uint32_t fallback) { |
| 334 | if (!matrixRef || CFGetTypeID(matrixRef) != CFStringGetTypeID()) { |
| 335 | return fallback; |
| 336 | } |
| 337 | CFStringRef ms = (CFStringRef)matrixRef; |
| 338 | if (CFEqual(ms, kCVImageBufferYCbCrMatrix_ITU_R_601_4) || |
| 339 | CFEqual(ms, kCVImageBufferYCbCrMatrix_SMPTE_240M_1995)) { |
| 340 | return 1u; // BT.601 |
| 341 | } |
| 342 | if (CFEqual(ms, kCVImageBufferYCbCrMatrix_ITU_R_2020)) { |
| 343 | return 2u; // BT.2020 |
| 344 | } |
| 345 | if (CFEqual(ms, kCVImageBufferYCbCrMatrix_ITU_R_709_2)) { |
| 346 | return 0u; // BT.709 |
| 347 | } |
| 348 | return fallback; |
| 349 | } |
| 350 | |
| 351 | static BOOL track_supports_nv12_8bit_420( |
| 352 | AVAssetTrack *track, |
| 353 | uint32_t rawW, |
| 354 | uint32_t rawH, |
| 355 | BOOL *outFullRange, |
| 356 | uint32_t *outDefaultMatrix |
| 357 | ) { |
| 358 | if (outFullRange) { |
| 359 | *outFullRange = NO; |
| 360 | } |
| 361 | // CoreVideo defaults untagged HD/4K to BT.709 and SD to BT.601. |
| 362 | uint32_t defaultMat = (rawW >= 1280 || rawH >= 720) ? 0u : 1u; |
| 363 | if (outDefaultMatrix) { |
| 364 | *outDefaultMatrix = defaultMat; |
| 365 | } |
| 366 | |
| 367 | NSArray *formatDescs = track.formatDescriptions; |
| 368 | if (!formatDescs || formatDescs.count == 0) { |
| 369 | return NO; |
| 370 | } |
| 371 | CMFormatDescriptionRef fmtDesc = (__bridge CMFormatDescriptionRef)formatDescs.firstObject; |
| 372 | if (!fmtDesc) { |
| 373 | return NO; |
| 374 | } |
| 375 | |
| 376 | FourCharCode subType = CMFormatDescriptionGetMediaSubType(fmtDesc); |
| 377 | const FourCharCode kHev1 = 0x68657631; // 'hev1' |
| 378 | BOOL is420Codec = |
| 379 | (subType == kCMVideoCodecType_H264) || |
| 380 | (subType == kCMVideoCodecType_HEVC) || |
| 381 | (subType == kHev1) || |
| 382 | (subType == kCMVideoCodecType_MPEG4Video); |
| 383 | if (!is420Codec) { |
| 384 | return NO; |
| 385 | } |
| 386 | |
| 387 | // Reject alpha-bearing tracks (ProRes 4444, HEVC with alpha, etc.). |
| 388 | CFTypeRef hasAlphaRef = CMFormatDescriptionGetExtension( |
| 389 | fmtDesc, kCMFormatDescriptionExtension_ContainsAlphaChannel); |
| 390 | if (hasAlphaRef && CFGetTypeID(hasAlphaRef) == CFBooleanGetTypeID() && |
| 391 | CFBooleanGetValue((CFBooleanRef)hasAlphaRef)) { |
| 392 | return NO; |
| 393 | } |
| 394 | CFTypeRef depthRef = CMFormatDescriptionGetExtension( |
| 395 | fmtDesc, kCMFormatDescriptionExtension_Depth); |
| 396 | if (depthRef && CFGetTypeID(depthRef) == CFNumberGetTypeID()) { |
| 397 | int depth = 0; |
| 398 | if (CFNumberGetValue((CFNumberRef)depthRef, kCFNumberIntType, &depth) && depth == 32) { |
| 399 | return NO; |
| 400 | } |
| 401 | } |
| 402 | |
| 403 | // Reject >8-bit (10-bit/12-bit) streams. |
| 404 | CFTypeRef bpcRef = CMFormatDescriptionGetExtension( |
| 405 | fmtDesc, kCMFormatDescriptionExtension_BitsPerComponent); |
| 406 | if (bpcRef && CFGetTypeID(bpcRef) == CFNumberGetTypeID()) { |
| 407 | int bpc = 0; |
| 408 | if (CFNumberGetValue((CFNumberRef)bpcRef, kCFNumberIntType, &bpc) && bpc != 8) { |
| 409 | return NO; |
| 410 | } |
| 411 | } |
| 412 | |
| 413 | // Reject HDR transfer functions (HLG, PQ, Linear) so CoreVideo handles HDR tone-mapping. |
| 414 | CFTypeRef tfRef = CMFormatDescriptionGetExtension( |
| 415 | fmtDesc, kCMFormatDescriptionExtension_TransferFunction); |
| 416 | if (tfRef && CFGetTypeID(tfRef) == CFStringGetTypeID()) { |
| 417 | CFStringRef tf = (CFStringRef)tfRef; |
| 418 | if (CFEqual(tf, kCMFormatDescriptionTransferFunction_ITU_R_2100_HLG) || |
| 419 | CFEqual(tf, kCMFormatDescriptionTransferFunction_SMPTE_ST_2084_PQ) || |
| 420 | CFEqual(tf, kCMFormatDescriptionTransferFunction_Linear)) { |
| 421 | return NO; |
| 422 | } |
| 423 | } |
| 424 | |
| 425 | // Inspect avcC / hvcC decoder config records to reject 10-bit or non-4:2:0 profiles |
| 426 | // even when BitsPerComponent is omitted by the container. |
| 427 | CFTypeRef atomsRef = CMFormatDescriptionGetExtension( |
| 428 | fmtDesc, kCMFormatDescriptionExtension_SampleDescriptionExtensionAtoms); |
| 429 | if (atomsRef && CFGetTypeID(atomsRef) == CFDictionaryGetTypeID()) { |
| 430 | NSDictionary *atoms = (__bridge NSDictionary *)atomsRef; |
| 431 | if (subType == kCMVideoCodecType_H264) { |
| 432 | NSData *avcC = atoms[@"avcC"]; |
| 433 | if ([avcC isKindOfClass:[NSData class]] && avcC.length >= 4) { |
| 434 | const uint8_t *b = (const uint8_t *)avcC.bytes; |
| 435 | uint8_t profile = b[1]; |
| 436 | // Reject High 10 (110), High 4:2:2 (122), CAVLC 4:4:4 (44), High 4:4:4 (144/244) |
| 437 | if (profile == 44 || profile == 110 || profile == 122 || profile == 144 || profile == 244) { |
| 438 | return NO; |
| 439 | } |
| 440 | } |
| 441 | } else if (subType == kCMVideoCodecType_HEVC || subType == kHev1) { |
| 442 | NSData *hvcC = atoms[@"hvcC"]; |
| 443 | if ([hvcC isKindOfClass:[NSData class]] && hvcC.length >= 22) { |
| 444 | const uint8_t *b = (const uint8_t *)hvcC.bytes; |
| 445 | uint8_t profileIdc = b[1] & 0x1F; |
| 446 | uint8_t chromaFormat = b[16] & 0x03; // 1 = 4:2:0 |
| 447 | uint8_t bitDepthLumaMinus8 = b[17] & 0x07; |
| 448 | uint8_t bitDepthChromaMinus8 = b[18] & 0x07; |
| 449 | if (profileIdc == 2 || chromaFormat != 1 || |
| 450 | bitDepthLumaMinus8 > 0 || bitDepthChromaMinus8 > 0) { |
| 451 | return NO; |
| 452 | } |
| 453 | } |
| 454 | } |
| 455 | } |
| 456 | |
| 457 | CFTypeRef fullRangeRef = CMFormatDescriptionGetExtension( |
| 458 | fmtDesc, kCMFormatDescriptionExtension_FullRangeVideo); |
| 459 | if (fullRangeRef && CFGetTypeID(fullRangeRef) == CFBooleanGetTypeID() && |
| 460 | CFBooleanGetValue((CFBooleanRef)fullRangeRef)) { |
| 461 | if (outFullRange) { |
| 462 | *outFullRange = YES; |
| 463 | } |
| 464 | } |
| 465 | |
| 466 | CFTypeRef matRef = CMFormatDescriptionGetExtension( |
| 467 | fmtDesc, kCMFormatDescriptionExtension_YCbCrMatrix); |
| 468 | if (outDefaultMatrix) { |
| 469 | *outDefaultMatrix = matrix_from_cf_string(matRef, defaultMat); |
| 470 | } |
| 471 | |
| 472 | return YES; |
| 473 | } |
| 474 | |
| 475 | static int copy_nv12_planes( |
| 476 | CVImageBufferRef imgBuf, |
| 477 | uint32_t expectedW, |
| 478 | uint32_t expectedH, |
| 479 | uint32_t defaultMatrix, |
| 480 | uint8_t *outY, |
| 481 | size_t outYLen, |
| 482 | uint8_t *outUv, |
| 483 | size_t outUvLen, |
| 484 | uint32_t *outMatrix, |
| 485 | uint32_t *outFullRange |
| 486 | ) { |
| 487 | if (!imgBuf || !outY || !outUv) { |
| 488 | return 0; |
| 489 | } |
| 490 | OSType pf = CVPixelBufferGetPixelFormatType(imgBuf); |
| 491 | if (pf != kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange && |
| 492 | pf != kCVPixelFormatType_420YpCbCr8BiPlanarFullRange) { |
| 493 | return 0; |
| 494 | } |
| 495 | if (!CVPixelBufferIsPlanar(imgBuf) || CVPixelBufferGetPlaneCount(imgBuf) < 2) { |
| 496 | return 0; |
| 497 | } |
| 498 | if (CVPixelBufferLockBaseAddress(imgBuf, kCVPixelBufferLock_ReadOnly) != kCVReturnSuccess) { |
| 499 | return 0; |
| 500 | } |
| 501 | |
| 502 | size_t yW = CVPixelBufferGetWidthOfPlane(imgBuf, 0); |
| 503 | size_t yH = CVPixelBufferGetHeightOfPlane(imgBuf, 0); |
| 504 | size_t yBpr = CVPixelBufferGetBytesPerRowOfPlane(imgBuf, 0); |
| 505 | const uint8_t *yBase = (const uint8_t *)CVPixelBufferGetBaseAddressOfPlane(imgBuf, 0); |
| 506 | |
| 507 | size_t uvW = CVPixelBufferGetWidthOfPlane(imgBuf, 1); |
| 508 | size_t uvH = CVPixelBufferGetHeightOfPlane(imgBuf, 1); |
| 509 | size_t uvBpr = CVPixelBufferGetBytesPerRowOfPlane(imgBuf, 1); |
| 510 | const uint8_t *uvBase = (const uint8_t *)CVPixelBufferGetBaseAddressOfPlane(imgBuf, 1); |
| 511 | |
| 512 | size_t expectedUvW = ((size_t)expectedW + 1) / 2; |
| 513 | size_t expectedUvH = ((size_t)expectedH + 1) / 2; |
| 514 | size_t yRequired = (size_t)expectedW * (size_t)expectedH; |
| 515 | size_t uvRowBytes = expectedUvW * 2; |
| 516 | size_t uvRequired = uvRowBytes * expectedUvH; |
| 517 | |
| 518 | int ok = 0; |
| 519 | if (yBase && uvBase && |
| 520 | yW >= (size_t)expectedW && yH >= (size_t)expectedH && |
| 521 | uvW >= expectedUvW && uvH >= expectedUvH && |
| 522 | yBpr >= (size_t)expectedW && uvBpr >= uvRowBytes && |
| 523 | outYLen >= yRequired && outUvLen >= uvRequired) { |
| 524 | if (yBpr == (size_t)expectedW) { |
| 525 | memcpy(outY, yBase, yRequired); |
| 526 | } else { |
| 527 | for (size_t r = 0; r < (size_t)expectedH; r++) { |
| 528 | memcpy(outY + r * (size_t)expectedW, yBase + r * yBpr, (size_t)expectedW); |
| 529 | } |
| 530 | } |
| 531 | if (uvBpr == uvRowBytes) { |
| 532 | memcpy(outUv, uvBase, uvRequired); |
| 533 | } else { |
| 534 | for (size_t r = 0; r < expectedUvH; r++) { |
| 535 | memcpy(outUv + r * uvRowBytes, uvBase + r * uvBpr, uvRowBytes); |
| 536 | } |
| 537 | } |
| 538 | ok = 1; |
| 539 | } |
| 540 | |
| 541 | CVPixelBufferUnlockBaseAddress(imgBuf, kCVPixelBufferLock_ReadOnly); |
| 542 | |
| 543 | if (ok) { |
| 544 | if (outFullRange) { |
| 545 | *outFullRange = (pf == kCVPixelFormatType_420YpCbCr8BiPlanarFullRange) ? 1u : 0u; |
| 546 | } |
| 547 | if (outMatrix) { |
| 548 | CFTypeRef matRef = CVBufferCopyAttachment(imgBuf, kCVImageBufferYCbCrMatrixKey, NULL); |
| 549 | *outMatrix = matrix_from_cf_string(matRef, defaultMatrix); |
| 550 | if (matRef) { |
| 551 | CFRelease(matRef); |
| 552 | } |
| 553 | } |
| 554 | } |
| 555 | return ok; |
| 556 | } |
| 557 | |
| 558 | AvVideoDecoder *av_video_open( |
| 559 | const char *path, |
| 560 | uint32_t *out_w, |
| 561 | uint32_t *out_h, |
| 562 | double *out_fps, |
| 563 | int64_t *out_nb_frames |
| 564 | ) { |
| 565 | if (!path || !out_w || !out_h || !out_fps || !out_nb_frames) { |
| 566 | return NULL; |
| 567 | } |
| 568 | @autoreleasepool { |
| 569 | NSString *nsPath = [NSString stringWithUTF8String:path]; |
| 570 | if (!nsPath) { |
| 571 | return NULL; |
| 572 | } |
| 573 | NSURL *url = [NSURL fileURLWithPath:nsPath]; |
| 574 | AVURLAsset *asset = [AVURLAsset |
| 575 | URLAssetWithURL:url |
| 576 | options:@{AVURLAssetPreferPreciseDurationAndTimingKey : @YES}]; |
| 577 | if (!asset) { |
| 578 | return NULL; |
| 579 | } |
| 580 | |
| 581 | NSArray<AVAssetTrack *> *tracks = [asset tracksWithMediaType:AVMediaTypeVideo]; |
| 582 | AVAssetTrack *track = tracks.firstObject; |
| 583 | if (!track) { |
| 584 | return NULL; |
| 585 | } |
| 586 | |
| 587 | CGSize natSize = track.naturalSize; |
| 588 | uint32_t natW = (uint32_t)llround(fabs(natSize.width)); |
| 589 | uint32_t natH = (uint32_t)llround(fabs(natSize.height)); |
| 590 | if (natW == 0 || natH == 0) { |
| 591 | return NULL; |
| 592 | } |
| 593 | |
| 594 | CGAffineTransform t = track.preferredTransform; |
| 595 | int rotation = -1; |
| 596 | uint32_t outW = natW; |
| 597 | uint32_t outH = natH; |
| 598 | if (fabs(t.a - 1.0) < 0.01 && fabs(t.b) < 0.01 && fabs(t.c) < 0.01 && |
| 599 | fabs(t.d - 1.0) < 0.01) { |
| 600 | rotation = 0; |
| 601 | } else if (fabs(t.a) < 0.01 && fabs(t.b - 1.0) < 0.01 && |
| 602 | fabs(t.c + 1.0) < 0.01 && fabs(t.d) < 0.01) { |
| 603 | rotation = 90; |
| 604 | outW = natH; |
| 605 | outH = natW; |
| 606 | } else if (fabs(t.a + 1.0) < 0.01 && fabs(t.b) < 0.01 && |
| 607 | fabs(t.c) < 0.01 && fabs(t.d + 1.0) < 0.01) { |
| 608 | rotation = 180; |
| 609 | } else if (fabs(t.a) < 0.01 && fabs(t.b + 1.0) < 0.01 && |
| 610 | fabs(t.c - 1.0) < 0.01 && fabs(t.d) < 0.01) { |
| 611 | rotation = 270; |
| 612 | outW = natH; |
| 613 | outH = natW; |
| 614 | } else { |
| 615 | // Unsupported affine transform (shear/non-90-deg); fall back to ffmpeg. |
| 616 | return NULL; |
| 617 | } |
| 618 | |
| 619 | double fps = (double)track.nominalFrameRate; |
| 620 | if (fps <= 0.0) { |
| 621 | CMTime minDur = track.minFrameDuration; |
| 622 | if (CMTIME_IS_NUMERIC(minDur) && minDur.value > 0 && minDur.timescale > 0) { |
| 623 | fps = (double)minDur.timescale / (double)minDur.value; |
| 624 | } |
| 625 | } |
| 626 | if (fps <= 0.0) { |
| 627 | fps = 30.0; |
| 628 | } |
| 629 | |
| 630 | CMTime dur = track.timeRange.duration; |
| 631 | if (!CMTIME_IS_NUMERIC(dur) || CMTimeGetSeconds(dur) <= 0.0) { |
| 632 | dur = asset.duration; |
| 633 | } |
| 634 | double durSec = CMTIME_IS_NUMERIC(dur) ? CMTimeGetSeconds(dur) : 0.0; |
| 635 | int64_t nbFrames = durSec > 0.0 ? (int64_t)llround(durSec * fps) : 0; |
| 636 | |
| 637 | double trackStartSec = 0.0; |
| 638 | if (CMTIME_IS_NUMERIC(track.timeRange.start)) { |
| 639 | double s = CMTimeGetSeconds(track.timeRange.start); |
| 640 | if (s > 0.0) { |
| 641 | trackStartSec = s; |
| 642 | } |
| 643 | } |
| 644 | |
| 645 | BOOL preferFullRange = NO; |
| 646 | uint32_t defaultMatrix = 0u; |
| 647 | BOOL useNv12 = track_supports_nv12_8bit_420( |
| 648 | track, natW, natH, &preferFullRange, &defaultMatrix); |
| 649 | |
| 650 | AvVideoDecoderObj *obj = [[AvVideoDecoderObj alloc] init]; |
| 651 | obj.asset = asset; |
| 652 | obj.track = track; |
| 653 | obj.width = outW; |
| 654 | obj.height = outH; |
| 655 | obj.rawWidth = natW; |
| 656 | obj.rawHeight = natH; |
| 657 | obj.rotation = rotation; |
| 658 | obj.useNv12 = useNv12; |
| 659 | obj.preferFullRange = preferFullRange; |
| 660 | obj.defaultMatrix = defaultMatrix; |
| 661 | obj.fps = fps; |
| 662 | obj.nbFrames = nbFrames; |
| 663 | obj.trackStartSec = trackStartSec; |
| 664 | obj.durSec = durSec; |
| 665 | obj.lastFrameIdx = -1; |
| 666 | obj.lastFrameRgba = nil; |
| 667 | obj.lastFrameY = nil; |
| 668 | obj.lastFrameUv = nil; |
| 669 | obj.lastFrameMatrix = defaultMatrix; |
| 670 | obj.lastFrameFullRange = preferFullRange ? 1u : 0u; |
| 671 | obj.hasLastFrame = NO; |
| 672 | obj.lastFrameIsEof = NO; |
| 673 | |
| 674 | // Verify AVAssetReader can actually open and decode this asset/codec. |
| 675 | // If NV12 output is rejected for an unusual stream, fall back seamlessly to 32BGRA. |
| 676 | if (![obj openReaderAtSeconds:0.0]) { |
| 677 | if (obj.useNv12) { |
| 678 | obj.useNv12 = NO; |
| 679 | if (![obj openReaderAtSeconds:0.0]) { |
| 680 | return NULL; |
| 681 | } |
| 682 | } else { |
| 683 | return NULL; |
| 684 | } |
| 685 | } |
| 686 | |
| 687 | *out_w = outW; |
| 688 | *out_h = outH; |
| 689 | *out_fps = fps; |
| 690 | *out_nb_frames = nbFrames; |
| 691 | return (AvVideoDecoder *)CFBridgingRetain(obj); |
| 692 | } |
| 693 | } |
| 694 | |
| 695 | int av_video_is_nv12( |
| 696 | AvVideoDecoder *dec, |
| 697 | uint32_t *out_raw_w, |
| 698 | uint32_t *out_raw_h, |
| 699 | uint32_t *out_rotation |
| 700 | ) { |
| 701 | if (!dec) { |
| 702 | return 0; |
| 703 | } |
| 704 | AvVideoDecoderObj *obj = (__bridge AvVideoDecoderObj *)dec; |
| 705 | if (!obj.useNv12) { |
| 706 | return 0; |
| 707 | } |
| 708 | if (out_raw_w) { |
| 709 | *out_raw_w = obj.rawWidth; |
| 710 | } |
| 711 | if (out_raw_h) { |
| 712 | *out_raw_h = obj.rawHeight; |
| 713 | } |
| 714 | if (out_rotation) { |
| 715 | *out_rotation = (uint32_t)obj.rotation; |
| 716 | } |
| 717 | return 1; |
| 718 | } |
| 719 | |
| 720 | static CMSampleBufferRef read_target_sample( |
| 721 | AvVideoDecoderObj *obj, |
| 722 | double targetPts, |
| 723 | double halfFrame, |
| 724 | BOOL *outHitEof |
| 725 | ) { |
| 726 | CMSampleBufferRef chosen = NULL; |
| 727 | CMSampleBufferRef lastSeen = NULL; |
| 728 | BOOL hitEof = NO; |
| 729 | |
| 730 | while (obj.reader.status == AVAssetReaderStatusReading) { |
| 731 | CMSampleBufferRef sb = [obj.output copyNextSampleBuffer]; |
| 732 | if (!sb) { |
| 733 | hitEof = (obj.reader.status == AVAssetReaderStatusCompleted); |
| 734 | break; |
| 735 | } |
| 736 | CMTime ptsTime = CMSampleBufferGetPresentationTimeStamp(sb); |
| 737 | double pts = CMTIME_IS_NUMERIC(ptsTime) ? CMTimeGetSeconds(ptsTime) : targetPts; |
| 738 | |
| 739 | if (pts + halfFrame >= targetPts) { |
| 740 | chosen = sb; |
| 741 | break; |
| 742 | } |
| 743 | if (lastSeen) { |
| 744 | CFRelease(lastSeen); |
| 745 | } |
| 746 | lastSeen = sb; |
| 747 | } |
| 748 | |
| 749 | if (!chosen && lastSeen) { |
| 750 | chosen = lastSeen; |
| 751 | lastSeen = NULL; |
| 752 | hitEof = YES; |
| 753 | } |
| 754 | if (lastSeen) { |
| 755 | CFRelease(lastSeen); |
| 756 | } |
| 757 | if (outHitEof) { |
| 758 | *outHitEof = hitEof || (obj.reader.status == AVAssetReaderStatusCompleted); |
| 759 | } |
| 760 | return chosen; |
| 761 | } |
| 762 | |
| 763 | static CMSampleBufferRef acquire_video_sample( |
| 764 | AvVideoDecoderObj *obj, |
| 765 | int64_t frame_idx, |
| 766 | BOOL *outHitEof, |
| 767 | BOOL *outAtEof |
| 768 | ) { |
| 769 | double fps = obj.fps > 0.0 ? obj.fps : 30.0; |
| 770 | double targetPts = obj.trackStartSec + ((double)frame_idx) / fps; |
| 771 | double halfFrame = 0.45 / fps; |
| 772 | |
| 773 | BOOL canAdvance = |
| 774 | obj.reader != nil && |
| 775 | obj.reader.status == AVAssetReaderStatusReading && |
| 776 | ((obj.lastFrameIdx == -1 && frame_idx <= 8) || |
| 777 | (obj.lastFrameIdx >= 0 && frame_idx > obj.lastFrameIdx && |
| 778 | frame_idx <= obj.lastFrameIdx + 8)); |
| 779 | |
| 780 | int64_t prevLastFrameIdx = obj.lastFrameIdx; |
| 781 | double seekSec = 0.0; |
| 782 | if (!canAdvance) { |
| 783 | seekSec = (frame_idx == 0) ? 0.0 : fmax(0.0, targetPts - (1.5 / fps)); |
| 784 | if (![obj openReaderAtSeconds:seekSec]) { |
| 785 | if (outHitEof) *outHitEof = NO; |
| 786 | if (outAtEof) *outAtEof = NO; |
| 787 | return NULL; |
| 788 | } |
| 789 | } |
| 790 | |
| 791 | BOOL hitEof = NO; |
| 792 | CMSampleBufferRef chosen = read_target_sample(obj, targetPts, halfFrame, &hitEof); |
| 793 | |
| 794 | // If requesting a frame past EOF (including sequential advance stepping past EOF or |
| 795 | // container duration overestimating the last video sample by > 4 frames), retry from |
| 796 | // endAnchor - 1.0 and, if that still misses, from the last known decoded frame timestamp. |
| 797 | if (!chosen && !obj.lastFrameIsEof && frame_idx > 0) { |
| 798 | double endAnchor = obj.durSec > 0.0 ? fmin(targetPts, obj.trackStartSec + obj.durSec) : targetPts; |
| 799 | double fallbackSec = fmax(0.0, endAnchor - 1.0); |
| 800 | if ((canAdvance || fallbackSec < seekSec - 0.05) && [obj openReaderAtSeconds:fallbackSec]) { |
| 801 | chosen = read_target_sample(obj, targetPts, halfFrame, &hitEof); |
| 802 | } |
| 803 | if (!chosen) { |
| 804 | double lastIdxSec = fmax( |
| 805 | 0.0, |
| 806 | prevLastFrameIdx >= 0 |
| 807 | ? obj.trackStartSec + (double)prevLastFrameIdx / fps - 0.1 |
| 808 | : 0.0 |
| 809 | ); |
| 810 | if ([obj openReaderAtSeconds:lastIdxSec]) { |
| 811 | chosen = read_target_sample(obj, targetPts, halfFrame, &hitEof); |
| 812 | } |
| 813 | } |
| 814 | } |
| 815 | |
| 816 | if (outHitEof) { |
| 817 | *outHitEof = hitEof; |
| 818 | } |
| 819 | if (!chosen && outAtEof) { |
| 820 | *outAtEof = (obj.reader != nil && obj.reader.status == AVAssetReaderStatusCompleted) || |
| 821 | (obj.nbFrames > 0 && frame_idx >= obj.nbFrames - 2); |
| 822 | } |
| 823 | return chosen; |
| 824 | } |
| 825 | |
| 826 | int av_video_decode_frame( |
| 827 | AvVideoDecoder *dec, |
| 828 | int64_t frame_idx, |
| 829 | uint8_t *out_rgba, |
| 830 | size_t out_len |
| 831 | ) { |
| 832 | if (!dec || !out_rgba) { |
| 833 | return 0; |
| 834 | } |
| 835 | @autoreleasepool { |
| 836 | AvVideoDecoderObj *obj = (__bridge AvVideoDecoderObj *)dec; |
| 837 | if (obj.useNv12) { |
| 838 | return 0; |
| 839 | } |
| 840 | if (frame_idx < 0) { |
| 841 | frame_idx = 0; |
| 842 | } |
| 843 | size_t required = (size_t)obj.width * (size_t)obj.height * 4; |
| 844 | if (out_len < required) { |
| 845 | return 0; |
| 846 | } |
| 847 | |
| 848 | BOOL hitEof = NO; |
| 849 | BOOL atEof = NO; |
| 850 | CMSampleBufferRef chosen = acquire_video_sample(obj, frame_idx, &hitEof, &atEof); |
| 851 | |
| 852 | if (!chosen) { |
| 853 | [obj closeReader]; |
| 854 | if (atEof && obj.hasLastFrame && frame_idx > 0 && obj.lastFrameRgba.length >= required) { |
| 855 | memcpy(out_rgba, obj.lastFrameRgba.bytes, required); |
| 856 | return 1; |
| 857 | } |
| 858 | return 0; |
| 859 | } |
| 860 | |
| 861 | CVImageBufferRef imgBuf = CMSampleBufferGetImageBuffer(chosen); |
| 862 | int ok = copy_bgra_to_rgba( |
| 863 | imgBuf, obj.width, obj.height, obj.rotation, out_rgba, out_len); |
| 864 | CFRelease(chosen); |
| 865 | |
| 866 | if (ok) { |
| 867 | if (hitEof || (!obj.lastFrameIsEof && (obj.nbFrames <= 0 || frame_idx >= obj.nbFrames - 4))) { |
| 868 | if (!obj.lastFrameRgba || obj.lastFrameRgba.length < required) { |
| 869 | obj.lastFrameRgba = [NSMutableData dataWithLength:required]; |
| 870 | } |
| 871 | if (obj.lastFrameRgba.length >= required) { |
| 872 | memcpy(obj.lastFrameRgba.mutableBytes, out_rgba, required); |
| 873 | obj.hasLastFrame = YES; |
| 874 | if (hitEof) { |
| 875 | obj.lastFrameIsEof = YES; |
| 876 | } |
| 877 | } |
| 878 | } |
| 879 | obj.lastFrameIdx = frame_idx; |
| 880 | } else { |
| 881 | [obj closeReader]; |
| 882 | } |
| 883 | return ok; |
| 884 | } |
| 885 | } |
| 886 | |
| 887 | int av_video_decode_nv12_frame( |
| 888 | AvVideoDecoder *dec, |
| 889 | int64_t frame_idx, |
| 890 | uint8_t *out_y, |
| 891 | size_t out_y_len, |
| 892 | uint8_t *out_uv, |
| 893 | size_t out_uv_len, |
| 894 | uint32_t *out_matrix, |
| 895 | uint32_t *out_full_range |
| 896 | ) { |
| 897 | if (!dec || !out_y || !out_uv) { |
| 898 | return 0; |
| 899 | } |
| 900 | @autoreleasepool { |
| 901 | AvVideoDecoderObj *obj = (__bridge AvVideoDecoderObj *)dec; |
| 902 | if (!obj.useNv12) { |
| 903 | return 0; |
| 904 | } |
| 905 | if (frame_idx < 0) { |
| 906 | frame_idx = 0; |
| 907 | } |
| 908 | size_t yRequired = (size_t)obj.rawWidth * (size_t)obj.rawHeight; |
| 909 | size_t uvW = ((size_t)obj.rawWidth + 1) / 2; |
| 910 | size_t uvH = ((size_t)obj.rawHeight + 1) / 2; |
| 911 | size_t uvRequired = uvW * uvH * 2; |
| 912 | if (out_y_len < yRequired || out_uv_len < uvRequired) { |
| 913 | return 0; |
| 914 | } |
| 915 | |
| 916 | BOOL hitEof = NO; |
| 917 | BOOL atEof = NO; |
| 918 | CMSampleBufferRef chosen = acquire_video_sample(obj, frame_idx, &hitEof, &atEof); |
| 919 | |
| 920 | if (!chosen) { |
| 921 | [obj closeReader]; |
| 922 | if (atEof && obj.hasLastFrame && frame_idx > 0 && |
| 923 | obj.lastFrameY.length >= yRequired && obj.lastFrameUv.length >= uvRequired) { |
| 924 | memcpy(out_y, obj.lastFrameY.bytes, yRequired); |
| 925 | memcpy(out_uv, obj.lastFrameUv.bytes, uvRequired); |
| 926 | if (out_matrix) { |
| 927 | *out_matrix = obj.lastFrameMatrix; |
| 928 | } |
| 929 | if (out_full_range) { |
| 930 | *out_full_range = obj.lastFrameFullRange; |
| 931 | } |
| 932 | return 1; |
| 933 | } |
| 934 | return 0; |
| 935 | } |
| 936 | |
| 937 | uint32_t matrix = obj.defaultMatrix; |
| 938 | uint32_t fullRange = obj.preferFullRange ? 1u : 0u; |
| 939 | CVImageBufferRef imgBuf = CMSampleBufferGetImageBuffer(chosen); |
| 940 | int ok = copy_nv12_planes( |
| 941 | imgBuf, |
| 942 | obj.rawWidth, |
| 943 | obj.rawHeight, |
| 944 | obj.defaultMatrix, |
| 945 | out_y, |
| 946 | out_y_len, |
| 947 | out_uv, |
| 948 | out_uv_len, |
| 949 | &matrix, |
| 950 | &fullRange |
| 951 | ); |
| 952 | CFRelease(chosen); |
| 953 | |
| 954 | if (ok) { |
| 955 | if (out_matrix) { |
| 956 | *out_matrix = matrix; |
| 957 | } |
| 958 | if (out_full_range) { |
| 959 | *out_full_range = fullRange; |
| 960 | } |
| 961 | if (hitEof || (!obj.lastFrameIsEof && (obj.nbFrames <= 0 || frame_idx >= obj.nbFrames - 4))) { |
| 962 | if (!obj.lastFrameY || obj.lastFrameY.length < yRequired) { |
| 963 | obj.lastFrameY = [NSMutableData dataWithLength:yRequired]; |
| 964 | } |
| 965 | if (!obj.lastFrameUv || obj.lastFrameUv.length < uvRequired) { |
| 966 | obj.lastFrameUv = [NSMutableData dataWithLength:uvRequired]; |
| 967 | } |
| 968 | if (obj.lastFrameY.length >= yRequired && obj.lastFrameUv.length >= uvRequired) { |
| 969 | memcpy(obj.lastFrameY.mutableBytes, out_y, yRequired); |
| 970 | memcpy(obj.lastFrameUv.mutableBytes, out_uv, uvRequired); |
| 971 | obj.lastFrameMatrix = matrix; |
| 972 | obj.lastFrameFullRange = fullRange; |
| 973 | obj.hasLastFrame = YES; |
| 974 | if (hitEof) { |
| 975 | obj.lastFrameIsEof = YES; |
| 976 | } |
| 977 | } |
| 978 | } |
| 979 | obj.lastFrameIdx = frame_idx; |
| 980 | } else { |
| 981 | [obj closeReader]; |
| 982 | } |
| 983 | return ok; |
| 984 | } |
| 985 | } |
| 986 | |
| 987 | void av_video_close(AvVideoDecoder *dec) { |
| 988 | if (!dec) { |
| 989 | return; |
| 990 | } |
| 991 | @autoreleasepool { |
| 992 | AvVideoDecoderObj *obj = (AvVideoDecoderObj *)CFBridgingRelease(dec); |
| 993 | [obj closeReader]; |
| 994 | } |
| 995 | } |
| 996 | |
| 997 | #pragma clang diagnostic pop |