QGMP4FrameHWDecoder.m 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  1. // QGMP4FrameHWDecoder.m
  2. // Tencent is pleased to support the open source community by making vap available.
  3. //
  4. // Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved.
  5. //
  6. // Licensed under the MIT License (the "License"); you may not use this file except in
  7. // compliance with the License. You may obtain a copy of the License at
  8. //
  9. // http://opensource.org/licenses/MIT
  10. //
  11. // Unless required by applicable law or agreed to in writing, software distributed under the License is
  12. // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
  13. // either express or implied. See the License for the specific language governing permissions and
  14. // limitations under the License.
  15. #import "QGMP4FrameHWDecoder.h"
  16. #import "QGVAPWeakProxy.h"
  17. #import "QGMP4AnimatedImageFrame.h"
  18. #import "QGBaseAnimatedImageFrame+Displaying.h"
  19. #import <VideoToolbox/VideoToolbox.h>
  20. #import "QGHWDMP4OpenGLView.h"
  21. #import "QGMP4Parser.h"
  22. #import "QGVAPSafeMutableArray.h"
  23. #import "NSNotificationCenter+VAPThreadSafe.h"
  24. #include <sys/sysctl.h>
  25. #import <AVFoundation/AVFoundation.h>
  26. @implementation UIDevice (HWD)
  27. - (BOOL)hwd_isSimulator {
  28. static dispatch_once_t token;
  29. static BOOL isSimulator = NO;
  30. dispatch_once(&token, ^{
  31. NSString *model = [self machineName];
  32. if ([model isEqualToString:@"x86_64"] || [model isEqualToString:@"i386"]) {
  33. isSimulator = YES;
  34. }
  35. });
  36. return isSimulator;
  37. }
  38. - (NSString *)machineName {
  39. static dispatch_once_t token;
  40. static NSString *name;
  41. dispatch_once(&token, ^{
  42. size_t size;
  43. sysctlbyname("hw.machine", NULL, &size, NULL, 0);
  44. char *machineName = malloc(size);
  45. sysctlbyname("hw.machine", machineName, &size, NULL, 0);
  46. name = [NSString stringWithUTF8String:machineName];
  47. free(machineName);
  48. });
  49. return name;
  50. }
  51. @end
  52. @interface NSArray (SafeOperation)
  53. @end
  54. @implementation NSArray (SafeOperation)
  55. - (id)safeObjectAtIndex:(NSUInteger)index
  56. {
  57. if (index >= self.count) {
  58. NSAssert(0, @"Error: access to array index which is beyond bounds! ");
  59. return nil;
  60. }
  61. return self[index];
  62. }
  63. @end
  64. @interface QGMP4FrameHWDecoder() {
  65. NSMutableArray *_buffers;
  66. int _videoStream;
  67. int _outputWidth, _outputHeight;
  68. OSStatus _status;
  69. BOOL _isFinish;
  70. VTDecompressionSessionRef _mDecodeSession;
  71. CMFormatDescriptionRef _mFormatDescription;
  72. NSInteger _finishFrameIndex;
  73. NSError *_constructErr;
  74. QGMP4ParserProxy *_mp4Parser;
  75. }
  76. @property (atomic, strong) dispatch_queue_t decodeQueue; //dispatch decode task
  77. @property (nonatomic, strong) NSData *ppsData; //Picture Parameter Set
  78. @property (nonatomic, strong) NSData *spsData; //Sequence Parameter Set
  79. /** Video Parameter Set */
  80. @property (nonatomic, strong) NSData *vpsData;
  81. @end
  82. NSString *const QGMP4HWDErrorDomain = @"QGMP4HWDErrorDomain";
  83. @implementation QGMP4FrameHWDecoder
  84. + (NSString *)errorDescriptionForCode:(QGMP4HWDErrorCode)errorCode {
  85. NSArray *errorDescs = @[@"文件不存在",@"非法文件格式",@"无法获取视频流信息",@"无法获取视频流",@"VTB创建desc失败",@"VTB创建session失败"];
  86. NSString *desc = @"";
  87. switch (errorCode) {
  88. case QGMP4HWDErrorCode_FileNotExist:
  89. desc = [errorDescs safeObjectAtIndex:0];
  90. break;
  91. case QGMP4HWDErrorCode_InvalidMP4File:
  92. desc = [errorDescs safeObjectAtIndex:1];
  93. break;
  94. case QGMP4HWDErrorCode_CanNotGetStreamInfo:
  95. desc = [errorDescs safeObjectAtIndex:2];
  96. break;
  97. case QGMP4HWDErrorCode_CanNotGetStream:
  98. desc = [errorDescs safeObjectAtIndex:3];
  99. break;
  100. case QGMP4HWDErrorCode_ErrorCreateVTBDesc:
  101. desc = [errorDescs safeObjectAtIndex:4];
  102. break;
  103. case QGMP4HWDErrorCode_ErrorCreateVTBSession:
  104. desc = [errorDescs safeObjectAtIndex:5];
  105. break;
  106. default:
  107. break;
  108. }
  109. return desc;
  110. }
  111. - (instancetype)initWith:(QGMP4HWDFileInfo *)fileInfo error:(NSError *__autoreleasing *)error{
  112. if (self = [super initWith:fileInfo error:error]) {
  113. _decodeQueue = dispatch_queue_create("com.qgame.vap.decode", DISPATCH_QUEUE_SERIAL);
  114. _mp4Parser = fileInfo.mp4Parser;
  115. BOOL isOpenSuccess = [self onInputStart];
  116. if (!isOpenSuccess) {
  117. VAP_Event(kQGVAPModuleCommon, @"onInputStart fail!");
  118. *error = _constructErr;
  119. self = nil;
  120. return nil;
  121. }
  122. [self registerNotification];
  123. }
  124. return self;
  125. }
  126. - (void)registerNotification {
  127. [[NSNotificationCenter defaultCenter] hwd_addSafeObserver:self selector:@selector(hwd_didReceiveEnterBackgroundNotification:) name:UIApplicationDidEnterBackgroundNotification object:nil];
  128. [[NSNotificationCenter defaultCenter] hwd_addSafeObserver:self selector:@selector(hwd_didReceiveEnterBackgroundNotification:) name:UIApplicationWillResignActiveNotification object:nil];
  129. }
  130. - (void)hwd_didReceiveEnterBackgroundNotification:(NSNotification *)notification {
  131. [self onInputEnd];
  132. }
  133. - (void)decodeFrame:(NSInteger)frameIndex buffers:(NSMutableArray *)buffers {
  134. if (frameIndex == self.currentDecodeFrame) {
  135. VAP_Event(kQGVAPModuleCommon, @"already in decode");
  136. return ;
  137. }
  138. self.currentDecodeFrame = frameIndex;
  139. _buffers = buffers;
  140. dispatch_async(self.decodeQueue, ^{
  141. [self _decodeFrame:frameIndex];
  142. });
  143. }
  144. - (void)_decodeFrame:(NSInteger)frameIndex {
  145. if (_isFinish) {
  146. return ;
  147. }
  148. if (!_buffers) {
  149. return ;
  150. }
  151. if (self.spsData == nil || self.ppsData == nil) {
  152. return ;
  153. }
  154. //解码开始时间
  155. NSDate *startDate = [NSDate date];
  156. NSData *packetData = [_mp4Parser readPacketOfSample:frameIndex];
  157. if (!packetData.length) {
  158. _finishFrameIndex = frameIndex;
  159. [self onInputEnd];
  160. return;
  161. }
  162. // 获取当前帧pts,pts是在parse mp4 box时得到的
  163. uint64_t currentPts = [_mp4Parser.videoSamples[frameIndex] pts];
  164. CVPixelBufferRef outputPixelBuffer = NULL;
  165. // 4. get NALUnit payload into a CMBlockBuffer,
  166. CMBlockBufferRef blockBuffer = NULL;
  167. _status = CMBlockBufferCreateWithMemoryBlock(kCFAllocatorDefault,
  168. (void *)packetData.bytes,
  169. packetData.length,
  170. kCFAllocatorNull, NULL, 0,
  171. packetData.length, 0,
  172. &blockBuffer);
  173. // 6. create a CMSampleBuffer.
  174. CMSampleBufferRef sampleBuffer = NULL;
  175. const size_t sampleSizeArray[] = {packetData.length};
  176. _status = CMSampleBufferCreateReady(kCFAllocatorDefault,
  177. blockBuffer,
  178. _mFormatDescription,
  179. 1, 0, NULL, 1, sampleSizeArray,
  180. &sampleBuffer);
  181. if (blockBuffer) {
  182. CFRelease(blockBuffer);
  183. }
  184. // 7. use VTDecompressionSessionDecodeFrame
  185. if (@available(iOS 9.0, *)) {
  186. __typeof(self) __weak weakSelf = self;
  187. VTDecodeFrameFlags flags = 0;
  188. VTDecodeInfoFlags flagOut = 0;
  189. VTDecompressionSessionDecodeFrameWithOutputHandler(_mDecodeSession, sampleBuffer, flags, &flagOut, ^(OSStatus status, VTDecodeInfoFlags infoFlags, CVImageBufferRef _Nullable imageBuffer, CMTime presentationTimeStamp, CMTime presentationDuration) {
  190. CFRelease(sampleBuffer);
  191. __typeof(self) strongSelf = weakSelf;
  192. if (strongSelf == nil) {
  193. return;
  194. }
  195. if(status == kVTInvalidSessionErr) {
  196. VAP_Error(kQGVAPModuleCommon, @"decompress fail! frame:%@ kVTInvalidSessionErr error:%@", @(frameIndex), @(status));
  197. } else if(status == kVTVideoDecoderBadDataErr) {
  198. VAP_Error(kQGVAPModuleCommon, @"decompress fail! frame:%@ kVTVideoDecoderBadDataErr error:%@", @(frameIndex), @(status));
  199. } else if(status != noErr) {
  200. VAP_Error(kQGVAPModuleCommon, @"decompress fail! frame:%@ error:%@", @(frameIndex), @(status));
  201. }
  202. QGMP4AnimatedImageFrame *newFrame = [[QGMP4AnimatedImageFrame alloc] init];
  203. // imagebuffer会在frame回收时释放
  204. CVPixelBufferRetain(imageBuffer);
  205. newFrame.pixelBuffer = imageBuffer;
  206. newFrame.frameIndex = frameIndex; //dts顺序
  207. NSTimeInterval decodeTime = [[NSDate date] timeIntervalSinceDate:startDate]*1000;
  208. newFrame.decodeTime = decodeTime;
  209. newFrame.defaultFps =(int) strongSelf->_mp4Parser.fps;
  210. newFrame.pts = currentPts;
  211. // 8. insert into buffer
  212. [strongSelf->_buffers addObject:newFrame];
  213. // 9. sort
  214. [strongSelf->_buffers sortUsingComparator:^NSComparisonResult(QGMP4AnimatedImageFrame * _Nonnull obj1, QGMP4AnimatedImageFrame * _Nonnull obj2) {
  215. return [@(obj1.pts) compare:@(obj2.pts)];
  216. }];
  217. });
  218. } else {
  219. // 7. use VTDecompressionSessionDecodeFrame
  220. VTDecodeFrameFlags flags = 0;
  221. VTDecodeInfoFlags flagOut = 0;
  222. _status = VTDecompressionSessionDecodeFrame(_mDecodeSession, sampleBuffer, flags, &outputPixelBuffer, &flagOut);
  223. if(_status == kVTInvalidSessionErr) {
  224. } else if(_status == kVTVideoDecoderBadDataErr) {
  225. } else if(_status != noErr) {
  226. }
  227. CFRelease(sampleBuffer);
  228. QGMP4AnimatedImageFrame *newFrame = [[QGMP4AnimatedImageFrame alloc] init];
  229. // imagebuffer会在frame回收时释放
  230. newFrame.pixelBuffer = outputPixelBuffer;
  231. newFrame.frameIndex = frameIndex;
  232. NSTimeInterval decodeTime = [[NSDate date] timeIntervalSinceDate:startDate]*1000;
  233. newFrame.decodeTime = decodeTime;
  234. newFrame.defaultFps = (int)_mp4Parser.fps;
  235. // 8. insert into buffer
  236. [_buffers addObject:newFrame];
  237. // 9. sort
  238. [_buffers sortUsingComparator:^NSComparisonResult(QGMP4AnimatedImageFrame * _Nonnull obj1, QGMP4AnimatedImageFrame * _Nonnull obj2) {
  239. return [@(obj1.pts) compare:@(obj2.pts)];
  240. }];
  241. }
  242. }
  243. #pragma mark - override
  244. - (BOOL)shouldStopDecode:(NSInteger)nextFrameIndex {
  245. return _isFinish;
  246. }
  247. - (BOOL)isFrameIndexBeyondEnd:(NSInteger)frameIndex {
  248. if (_finishFrameIndex > 0) {
  249. return (frameIndex >= _finishFrameIndex);
  250. }
  251. return NO;
  252. }
  253. -(void)dealloc {
  254. [[NSNotificationCenter defaultCenter] removeObserver:self];
  255. [self _onInputEnd];
  256. self.fileInfo.occupiedCount --;
  257. if (self.fileInfo.occupiedCount <= 0) {
  258. }
  259. }
  260. #pragma mark - private methods
  261. - (BOOL)onInputStart {
  262. NSFileManager *fileMgr = [NSFileManager defaultManager];
  263. if (![fileMgr fileExistsAtPath:self.fileInfo.filePath]) {
  264. _constructErr = [NSError errorWithDomain:QGMP4HWDErrorDomain code:QGMP4HWDErrorCode_FileNotExist userInfo:[self errorUserInfo]];
  265. return NO;
  266. }
  267. _isFinish = NO;
  268. self.vpsData = nil;
  269. self.spsData = nil;
  270. self.ppsData = nil;
  271. _outputWidth = (int)_mp4Parser.picWidth;
  272. _outputHeight = (int)_mp4Parser.picHeight;
  273. BOOL paramsSetInitSuccess = [self initPPSnSPS];
  274. return paramsSetInitSuccess;
  275. }
  276. - (BOOL)initPPSnSPS {
  277. VAP_Info(kQGVAPModuleCommon, @"initPPSnSPS");
  278. if (self.spsData && self.ppsData) {
  279. VAP_Error(kQGVAPModuleCommon, @"sps&pps is already has value.");
  280. return YES;
  281. }
  282. self.spsData = _mp4Parser.spsData;
  283. self.ppsData = _mp4Parser.ppsData;
  284. self.vpsData = _mp4Parser.vpsData;
  285. // 2. create CMFormatDescription
  286. if (self.spsData != nil && self.ppsData != nil && _mp4Parser.videoCodecID != QGMP4VideoStreamCodecIDUnknown) {
  287. if (_mp4Parser.videoCodecID == QGMP4VideoStreamCodecIDH264) {
  288. const uint8_t* const parameterSetPointers[2] = { (const uint8_t*)[self.spsData bytes], (const uint8_t*)[self.ppsData bytes] };
  289. const size_t parameterSetSizes[2] = { [self.spsData length], [self.ppsData length] };
  290. _status = CMVideoFormatDescriptionCreateFromH264ParameterSets(kCFAllocatorDefault,
  291. 2,
  292. parameterSetPointers,
  293. parameterSetSizes,
  294. 4,
  295. &_mFormatDescription);
  296. if (_status != noErr) {
  297. VAP_Event(kQGVAPModuleCommon, @"CMVideoFormatDescription. Creation: %@.", (_status == noErr) ? @"successfully." : @"failed.");
  298. _constructErr = [NSError errorWithDomain:QGMP4HWDErrorDomain code:QGMP4HWDErrorCode_ErrorCreateVTBDesc userInfo:[self errorUserInfo]];
  299. return NO;
  300. }
  301. } else if (_mp4Parser.videoCodecID == QGMP4VideoStreamCodecIDH265) {
  302. if (@available(iOS 11.0, *)) {
  303. if(VTIsHardwareDecodeSupported(kCMVideoCodecType_HEVC)) {
  304. const uint8_t* const parameterSetPointers[3] = {(const uint8_t*)[self.vpsData bytes], (const uint8_t*)[self.spsData bytes], (const uint8_t*)[self.ppsData bytes]};
  305. const size_t parameterSetSizes[3] = {[self.vpsData length], [self.spsData length], [self.ppsData length]};
  306. _status = CMVideoFormatDescriptionCreateFromHEVCParameterSets(kCFAllocatorDefault,
  307. 3, // parameter_set_count
  308. parameterSetPointers, // &parameter_set_pointers
  309. parameterSetSizes, // &parameter_set_sizes
  310. 4, // nal_unit_header_length
  311. NULL,
  312. &_mFormatDescription);
  313. if (_status != noErr) {
  314. VAP_Event(kQGVAPModuleCommon, @"CMVideoFormatDescription. Creation: %@.", (_status == noErr) ? @"successfully." : @"failed.");
  315. _constructErr = [NSError errorWithDomain:QGMP4HWDErrorDomain code:QGMP4HWDErrorCode_ErrorCreateVTBDesc userInfo:[self errorUserInfo]];
  316. return NO;
  317. }
  318. } else {
  319. VAP_Event(kQGVAPModuleCommon, @"H.265 decoding is un-supported because of the hardware");
  320. return NO;
  321. }
  322. } else {
  323. VAP_Event(kQGVAPModuleCommon, @"System version is too low to support H.265 decoding");
  324. return NO;
  325. }
  326. }
  327. }
  328. // 3. create VTDecompressionSession
  329. CFDictionaryRef attrs = NULL;
  330. const void *keys[] = {kCVPixelBufferPixelFormatTypeKey};
  331. // kCVPixelFormatType_420YpCbCr8Planar is YUV420
  332. // kCVPixelFormatType_420YpCbCr8BiPlanarFullRange is NV12
  333. uint32_t v = kCVPixelFormatType_420YpCbCr8BiPlanarFullRange;
  334. const void *values[] = { CFNumberCreate(NULL, kCFNumberSInt32Type, &v) };
  335. attrs = CFDictionaryCreate(NULL, keys, values, 1, NULL, NULL);
  336. if ([UIDevice currentDevice].systemVersion.floatValue >= 9.0) {
  337. _status = VTDecompressionSessionCreate(kCFAllocatorDefault,
  338. _mFormatDescription,
  339. NULL,
  340. attrs,
  341. NULL,
  342. &_mDecodeSession);
  343. if (_status != noErr) {
  344. CFRelease(attrs);
  345. _constructErr = [NSError errorWithDomain:QGMP4HWDErrorDomain code:QGMP4HWDErrorCode_ErrorCreateVTBSession userInfo:[self errorUserInfo]];
  346. return NO;
  347. }
  348. } else {
  349. VTDecompressionOutputCallbackRecord callBackRecord;
  350. callBackRecord.decompressionOutputCallback = didDecompress;
  351. callBackRecord.decompressionOutputRefCon = NULL;
  352. _status = VTDecompressionSessionCreate(kCFAllocatorDefault,
  353. _mFormatDescription,
  354. NULL, attrs,
  355. &callBackRecord,
  356. &_mDecodeSession);
  357. if (_status != noErr) {
  358. CFRelease(attrs);
  359. _constructErr = [NSError errorWithDomain:QGMP4HWDErrorDomain code:QGMP4HWDErrorCode_ErrorCreateVTBSession userInfo:[self errorUserInfo]];
  360. return NO;
  361. }
  362. }
  363. CFRelease(attrs);
  364. return YES;
  365. }
  366. - (void)_onInputEnd {
  367. if (_isFinish) {
  368. return ;
  369. }
  370. _isFinish = YES;
  371. if (_mDecodeSession) {
  372. VTDecompressionSessionWaitForAsynchronousFrames(_mDecodeSession);
  373. VTDecompressionSessionInvalidate(_mDecodeSession);
  374. CFRelease(_mDecodeSession);
  375. _mDecodeSession = NULL;
  376. }
  377. if (self.spsData || self.ppsData || self.vpsData) {
  378. self.spsData = nil;
  379. self.ppsData = nil;
  380. self.vpsData = nil;
  381. }
  382. if (_mFormatDescription) {
  383. CFRelease(_mFormatDescription);
  384. _mFormatDescription = NULL;
  385. }
  386. }
  387. - (void)onInputEnd {
  388. //为确保任务停止,必须同步执行
  389. __weak __typeof(self) weakSelf = self;
  390. if ([NSThread isMainThread]) {
  391. dispatch_sync(self.decodeQueue, ^{
  392. [weakSelf _onInputEnd];
  393. });
  394. } else {
  395. dispatch_async(self.decodeQueue, ^{
  396. [weakSelf _onInputEnd];
  397. });
  398. }
  399. }
  400. //decode callback
  401. void didDecompress(void *decompressionOutputRefCon, void *sourceFrameRefCon, OSStatus status, VTDecodeInfoFlags infoFlags, CVImageBufferRef pixelBuffer, CMTime presentationTimeStamp, CMTime presentationDuration ){
  402. CVPixelBufferRef *outputPixelBuffer = (CVPixelBufferRef *)sourceFrameRefCon;
  403. *outputPixelBuffer = CVPixelBufferRetain(pixelBuffer);
  404. }
  405. - (NSDictionary *)errorUserInfo {
  406. NSDictionary *userInfo = @{@"location" : self.fileInfo.filePath ? : @""};
  407. return userInfo;
  408. }
  409. @end