| 7 | #import <Foundation/Foundation.h> |
| 8 | #import "TGVVideoSource.h" |
| 9 | #include "VideoToolboxEncoderSource.h" |
| 10 | #include "../../PrivateDefines.h" |
| 11 | #include "../../logging.h" |
| 12 |
| 13 | using namespace tgvoip; |
| 14 | using namespace tgvoip::video; |
| 15 |
| 16 | #define CHECK_ERR(err, msg) if(err!=noErr){LOGE("VideoToolboxEncoder: " msg " failed: %d", err); return;} |
| 17 |
| 18 | VideoToolboxEncoderSource::VideoToolboxEncoderSource(TGVVideoSource* parent){ |
| 19 | objcObject=parent; |
| 20 | } |
| 21 |
| 22 | VideoToolboxEncoderSource::~VideoToolboxEncoderSource(){ |
| 23 | if(session){ |
| 24 | CFRelease(session); |
| 25 | session=NULL; |
| 26 | } |
| 27 | } |
| 28 |
| 29 | void VideoToolboxEncoderSource::Start(){ |
| 30 |
| 31 | } |
| 32 |
| 33 | void VideoToolboxEncoderSource::Stop(){ |
| 34 |
| 35 | } |
| 36 |
| 37 | void VideoToolboxEncoderSource::Reset(uint32_t codec, int maxResolution){ |
| 38 | if(session){ |
| 39 | LOGV("Releasing old compression session"); |
| 40 | //VTCompressionSessionCompleteFrames(session, kCMTimeInvalid); |
| 41 | VTCompressionSessionInvalidate(session); |
| 42 | CFRelease(session); |
| 43 | session=NULL; |
| 44 | LOGV("Released compression session"); |
| 45 | } |
| 46 | CMVideoCodecType codecType; |
| 47 | switch(codec){ |
| 48 | case CODEC_AVC: |
| 49 | codecType=kCMVideoCodecType_H264; |
| 50 | break; |
| 51 | case CODEC_HEVC: |
| 52 | codecType=kCMVideoCodecType_HEVC; |
| 53 | break; |
| 54 | default: |
| 55 | LOGE("VideoToolboxEncoder: Unsupported codec"); |
| 56 | return; |
| 57 | } |
| 58 | needUpdateStreamParams=true; |
| 59 | this->codec=codec; |
| 60 | // typedef void (*VTCompressionOutputCallback)(void *outputCallbackRefCon, void *sourceFrameRefCon, OSStatus status, VTEncodeInfoFlags infoFlags, CMSampleBufferRef sampleBuffer); |
| 61 | uint32_t width, height; |
| 62 | switch(maxResolution){ |
| 63 | case INIT_VIDEO_RES_1080: |
| 64 | width=1920; |
| 65 | height=1080; |
| 66 | break; |
| 67 | case INIT_VIDEO_RES_720: |
| 68 | width=1280; |
| 69 | height=720; |
| 70 | break; |
| 71 | case INIT_VIDEO_RES_480: |
| 72 | width=854; |
| 73 | height=480; |
| 74 | break; |
| 75 | case INIT_VIDEO_RES_360: |
| 76 | default: |
| 77 | width=640; |
| 78 | height=360; |
| 79 | break; |
| 80 | } |
| 81 | unsigned int targetFrameRate=15; |
| 82 | if(codec==CODEC_HEVC && maxResolution>=INIT_VIDEO_RES_720) |
| 83 | targetFrameRate=30; |
| 84 | if(lastFrameRate!=targetFrameRate){ |
| 85 | lastFrameRate=targetFrameRate; |
| 86 | [objcObject _requestFrameRate:targetFrameRate]; |
| 87 | } |
| 88 |
| 89 | OSStatus status=VTCompressionSessionCreate(NULL, width, height, codecType, NULL, NULL, NULL, [](void *outputCallbackRefCon, void *sourceFrameRefCon, OSStatus status, VTEncodeInfoFlags infoFlags, CMSampleBufferRef sampleBuffer){ |
| 90 | reinterpret_cast<VideoToolboxEncoderSource*>(outputCallbackRefCon)->EncoderCallback(status, sampleBuffer, infoFlags); |
| 91 | }, this, &session); |
| 92 | if(status!=noErr){ |
| 93 | LOGE("VTCompressionSessionCreate failed: %d", status); |
| 94 | return; |
| 95 | } |
| 96 | LOGD("Created VTCompressionSession"); |
| 97 | status=VTSessionSetProperty(session, kVTCompressionPropertyKey_AllowFrameReordering, kCFBooleanFalse); |
| 98 | CHECK_ERR(status, "VTSessionSetProperty(AllowFrameReordering)"); |
| 99 | int64_t interval=5; |
| 100 | status=VTSessionSetProperty(session, kVTCompressionPropertyKey_MaxKeyFrameIntervalDuration, (__bridge CFTypeRef)@(interval)); |
| 101 | CHECK_ERR(status, "VTSessionSetProperty(MaxKeyFrameIntervalDuration)"); |
| 102 | SetEncoderBitrateAndLimit(lastBitrate); |
| 103 | status=VTSessionSetProperty(session, kVTCompressionPropertyKey_RealTime, kCFBooleanTrue); |
| 104 | CHECK_ERR(status, "VTSessionSetProperty(RealTime)"); |
| 105 | LOGD("VTCompressionSession initialized"); |
| 106 |
| 107 | // TODO change camera frame rate dynamically based on resolution + codec |
| 108 | } |
| 109 |
| 110 | void VideoToolboxEncoderSource::RequestKeyFrame(){ |
| 111 | keyframeRequested=true; |
| 112 | } |
| 113 |
| 114 | void VideoToolboxEncoderSource::EncodeFrame(CMSampleBufferRef frame){ |
| 115 | if(!session) |
| 116 | return; |
| 117 | CMFormatDescriptionRef format=CMSampleBufferGetFormatDescription(frame); |
| 118 | CMMediaType type=CMFormatDescriptionGetMediaType(format); |
| 119 | if(type!=kCMMediaType_Video){ |
| 120 | //LOGW("Received non-video CMSampleBuffer"); |
| 121 | return; |
| 122 | } |
| 123 | if(bitrateChangeRequested){ |
| 124 | LOGI("VideoToolboxEocnder: setting bitrate to %u", bitrateChangeRequested); |
| 125 | SetEncoderBitrateAndLimit(bitrateChangeRequested); |
| 126 | lastBitrate=bitrateChangeRequested; |
| 127 | bitrateChangeRequested=0; |
| 128 | } |
| 129 | CFDictionaryRef frameProps=NULL; |
| 130 | if(keyframeRequested){ |
| 131 | LOGI("VideoToolboxEncoder: requesting keyframe"); |
| 132 | const void* keys[]={kVTEncodeFrameOptionKey_ForceKeyFrame}; |
| 133 | const void* values[]={kCFBooleanTrue}; |
| 134 | frameProps=CFDictionaryCreate(NULL, keys, values, 1, NULL, NULL); |
| 135 | keyframeRequested=false; |
| 136 | } |
| 137 |
| 138 | //CMVideoDimensions size=CMVideoFormatDescriptionGetDimensions(format); |
| 139 | //LOGD("EncodeFrame %d x %d", size.width, size.height); |
| 140 | CVImageBufferRef imgBuffer=CMSampleBufferGetImageBuffer(frame); |
| 141 | //OSType pixFmt=CVPixelBufferGetPixelFormatType(imgBuffer); |
| 142 | //LOGV("pixel format: %c%c%c%c", PRINT_FOURCC(pixFmt)); |
| 143 | OSStatus status=VTCompressionSessionEncodeFrame(session, imgBuffer, CMSampleBufferGetPresentationTimeStamp(frame), CMSampleBufferGetDuration(frame), frameProps, NULL, NULL); |
| 144 | CHECK_ERR(status, "VTCompressionSessionEncodeFrame"); |
| 145 | if(frameProps) |
| 146 | CFRelease(frameProps); |
| 147 | } |
| 148 |
| 149 | void VideoToolboxEncoderSource::SetBitrate(uint32_t bitrate){ |
| 150 | bitrateChangeRequested=bitrate; |
| 151 | } |
| 152 |
| 153 | void VideoToolboxEncoderSource::EncoderCallback(OSStatus status, CMSampleBufferRef buffer, VTEncodeInfoFlags flags){ |
| 154 | if(status!=noErr){ |
| 155 | LOGE("EncoderCallback error: %d", status); |
| 156 | return; |
| 157 | } |
| 158 | if(flags & kVTEncodeInfo_FrameDropped){ |
| 159 | LOGW("VideoToolboxEncoder: Frame dropped"); |
| 160 | } |
| 161 | if(!CMSampleBufferGetNumSamples(buffer)){ |
| 162 | LOGW("Empty CMSampleBuffer"); |
| 163 | return; |
| 164 | } |
| 165 | if(!callback){ |
| 166 | return; |
| 167 | } |
| 168 | const uint8_t startCode[]={0, 0, 0, 1}; |
| 169 | if(needUpdateStreamParams){ |
| 170 | LOGI("VideoToolboxEncoder: Updating stream params"); |
| 171 | CMFormatDescriptionRef format=CMSampleBufferGetFormatDescription(buffer); |
| 172 | CMVideoDimensions size=CMVideoFormatDescriptionGetDimensions(format); |
| 173 | width=size.width; |
| 174 | height=size.height; |
| 175 | csd.clear(); |
| 176 | if(codec==CODEC_AVC){ |
| 177 | for(size_t i=0;i<2;i++){ |
| 178 | const uint8_t* ps=NULL; |
| 179 | size_t pl=0; |
| 180 | status=CMVideoFormatDescriptionGetH264ParameterSetAtIndex(format, i, &ps, &pl, NULL, NULL); |
| 181 | CHECK_ERR(status, "CMVideoFormatDescriptionGetH264ParameterSetAtIndex"); |
| 182 | Buffer b(pl+4); |
| 183 | b.CopyFrom(ps, 4, pl); |
| 184 | b.CopyFrom(startCode, 0, 4); |
| 185 | csd.push_back(std::move(b)); |
| 186 | } |
| 187 | }else if(codec==CODEC_HEVC){ |
| 188 | BufferOutputStream csdBuf(1024); |
| 189 | for(size_t i=0;i<3;i++){ |
| 190 | const uint8_t* ps=NULL; |
| 191 | size_t pl=0; |
| 192 | status=CMVideoFormatDescriptionGetHEVCParameterSetAtIndex(format, i, &ps, &pl, NULL, NULL); |
| 193 | CHECK_ERR(status, "CMVideoFormatDescriptionGetHEVCParameterSetAtIndex"); |
| 194 | csdBuf.WriteBytes(startCode, 4); |
| 195 | csdBuf.WriteBytes(ps, pl); |
| 196 | } |
| 197 | csd.push_back(std::move(csdBuf)); |
| 198 | } |
| 199 | needUpdateStreamParams=false; |
| 200 | } |
| 201 | CMBlockBufferRef blockBuffer=CMSampleBufferGetDataBuffer(buffer); |
| 202 | size_t len=CMBlockBufferGetDataLength(blockBuffer); |
| 203 |
| 204 | int frameFlags=0; |
| 205 | CFArrayRef attachmentsArray=CMSampleBufferGetSampleAttachmentsArray(buffer, 0); |
| 206 | if(attachmentsArray && CFArrayGetCount(attachmentsArray)){ |
| 207 | CFBooleanRef notSync; |
| 208 | CFDictionaryRef dict=(CFDictionaryRef)CFArrayGetValueAtIndex(attachmentsArray, 0); |
| 209 | BOOL keyExists=CFDictionaryGetValueIfPresent(dict, kCMSampleAttachmentKey_NotSync, (const void **)¬Sync); |
| 210 | if(!keyExists || !CFBooleanGetValue(notSync)){ |
| 211 | frameFlags |= VIDEO_FRAME_FLAG_KEYFRAME; |
| 212 | } |
| 213 | }else{ |
| 214 | frameFlags |= VIDEO_FRAME_FLAG_KEYFRAME; |
| 215 | } |
| 216 |
| 217 | Buffer frame(len); |
| 218 | CMBlockBufferCopyDataBytes(blockBuffer, 0, len, *frame); |
| 219 | uint32_t offset=0; |
| 220 | while(offset<len){ |
| 221 | uint32_t nalLen=CFSwapInt32BigToHost(*reinterpret_cast<uint32_t*>(*frame+offset)); |
| 222 | //LOGV("NAL length %u", nalLen); |
| 223 | frame.CopyFrom(startCode, offset, 4); |
| 224 | offset+=nalLen+4; |
| 225 | } |
| 226 | callback(std::move(frame), frameFlags, rotation); |
| 227 |
| 228 | //LOGV("EncoderCallback: %u bytes total", (unsigned int)len); |
| 229 | } |
| 230 |
| 231 | void VideoToolboxEncoderSource::SetEncoderBitrateAndLimit(uint32_t bitrate){ |
| 232 | OSStatus status=VTSessionSetProperty(session, kVTCompressionPropertyKey_AverageBitRate, (__bridge CFTypeRef)@(bitrate)); |
| 233 | CHECK_ERR(status, "VTSessionSetProperty(AverageBitRate)"); |
| 234 |
| 235 | int64_t dataLimitValue=(int64_t)(bitrate/8); |
| 236 | CFNumberRef bytesPerSecond=CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt64Type, &dataLimitValue); |
| 237 | int64_t oneValue=1; |
| 238 | CFNumberRef one=CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt64Type, &oneValue); |
| 239 | const void* numbers[]={bytesPerSecond, one}; |
| 240 | CFArrayRef limits=CFArrayCreate(NULL, numbers, 2, &kCFTypeArrayCallBacks); |
| 241 | status=VTSessionSetProperty(session, kVTCompressionPropertyKey_DataRateLimits, limits); |
| 242 | CFRelease(bytesPerSecond); |
| 243 | CFRelease(one); |
| 244 | CFRelease(limits); |
| 245 | CHECK_ERR(status, "VTSessionSetProperty(DataRateLimits"); |
| 246 | } |
| 247 |
| 248 | bool VideoToolboxEncoderSource::SupportsFullHD(){ |
| 249 | std::vector<uint32_t> encoders=GetAvailableEncoders(); |
| 250 | return std::find(encoders.begin(), encoders.end(), CODEC_HEVC)!=encoders.end(); |
| 251 | } |
| 252 |
| 253 | void VideoToolboxEncoderSource::SetStreamPaused(bool paused){ |
| 254 |
| 255 | } |
| 256 |
| 257 | std::vector<uint32_t> VideoToolboxEncoderSource::GetAvailableEncoders(){ |
| 258 | std::vector<uint32_t> res; |
| 259 | res.push_back(CODEC_AVC); |
| 260 | CFArrayRef encoders; |
| 261 | OSStatus status=VTCopyVideoEncoderList(NULL, &encoders); |
| 262 | for(CFIndex i=0;i<CFArrayGetCount(encoders);i++){ |
| 263 | CFDictionaryRef v=(CFDictionaryRef)CFArrayGetValueAtIndex(encoders, i); |
| 264 | NSDictionary* encoder=(__bridge NSDictionary*)v; |
| 265 | //NSString* name=(NSString*)CFDictionaryGetValue(v, kVTVideoEncoderList_EncoderName); |
| 266 | uint32_t codecType=[(NSNumber*)encoder[(NSString*)kVTVideoEncoderList_CodecType] intValue]; |
| 267 | //LOGV("Encoders[%u]: %s, %c%c%c%c", i, [(NSString*)encoder[(NSString*)kVTVideoEncoderList_EncoderName] cStringUsingEncoding:NSUTF8StringEncoding], PRINT_FOURCC(codecType)); |
| 268 | if(codecType==kCMVideoCodecType_HEVC){ |
| 269 | res.push_back(CODEC_HEVC); |
| 270 | break; |
| 271 | } |
| 272 | } |
| 273 | CFRelease(encoders); |
| 274 | return res; |
| 275 | } |
| 276 |