encoder.c 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766
  1. #include <obs-module.h>
  2. #include <util/darray.h>
  3. #include <util/platform.h>
  4. #include <obs-avc.h>
  5. #include <CoreFoundation/CoreFoundation.h>
  6. #include <VideoToolbox/VideoToolbox.h>
  7. #include <VideoToolbox/VTVideoEncoderList.h>
  8. #include <CoreMedia/CoreMedia.h>
  9. #include <util/apple/cfstring-utils.h>
  10. #include <assert.h>
  11. #define VT_LOG(level, format, ...) \
  12. blog(level, "[VideoToolbox encoder]: " format, ##__VA_ARGS__)
  13. #define VT_LOG_ENCODER(encoder, codec_type, level, format, ...) \
  14. blog(level, "[VideoToolbox %s: '%s']: " format, \
  15. obs_encoder_get_name(encoder), \
  16. codec_type_to_print_fmt(codec_type), ##__VA_ARGS__)
  17. #define VT_BLOG(level, format, ...) \
  18. VT_LOG_ENCODER(enc->encoder, enc->codec_type, level, format, \
  19. ##__VA_ARGS__)
  20. struct vt_encoder_type_data {
  21. const char *disp_name;
  22. const char *id;
  23. CMVideoCodecType codec_type;
  24. bool hardware_accelerated;
  25. };
  26. struct vt_prores_encoder_data {
  27. FourCharCode codec_type;
  28. CFStringRef encoder_id;
  29. };
  30. static DARRAY(struct vt_prores_encoder_data) vt_prores_hardware_encoder_list;
  31. static DARRAY(struct vt_prores_encoder_data) vt_prores_software_encoder_list;
  32. #ifdef __aarch64__
  33. bool is_apple_silicon = true;
  34. #else
  35. bool is_apple_silicon = false;
  36. #endif
  37. struct vt_encoder {
  38. obs_encoder_t *encoder;
  39. const char *vt_encoder_id;
  40. uint32_t width;
  41. uint32_t height;
  42. uint32_t keyint;
  43. uint32_t fps_num;
  44. uint32_t fps_den;
  45. const char *rate_control;
  46. uint32_t bitrate;
  47. float quality;
  48. bool limit_bitrate;
  49. uint32_t rc_max_bitrate;
  50. double rc_max_bitrate_window;
  51. const char *profile;
  52. CMVideoCodecType codec_type;
  53. bool bframes;
  54. int vt_pix_fmt;
  55. enum video_colorspace colorspace;
  56. VTCompressionSessionRef session;
  57. CMSimpleQueueRef queue;
  58. bool hw_enc;
  59. DARRAY(uint8_t) packet_data;
  60. DARRAY(uint8_t) extra_data;
  61. };
  62. static const char *codec_type_to_print_fmt(CMVideoCodecType codec_type)
  63. {
  64. switch (codec_type) {
  65. case kCMVideoCodecType_H264:
  66. return "h264";
  67. case kCMVideoCodecType_HEVC:
  68. return "hevc";
  69. case kCMVideoCodecType_AppleProRes4444XQ:
  70. return "ap4x";
  71. case kCMVideoCodecType_AppleProRes4444:
  72. return "ap4h";
  73. case kCMVideoCodecType_AppleProRes422Proxy:
  74. return "apco";
  75. case kCMVideoCodecType_AppleProRes422LT:
  76. return "apcs";
  77. case kCMVideoCodecType_AppleProRes422:
  78. return "apcn";
  79. case kCMVideoCodecType_AppleProRes422HQ:
  80. return "apch";
  81. default:
  82. return "";
  83. }
  84. }
  85. static void log_osstatus(int log_level, struct vt_encoder *enc,
  86. const char *context, OSStatus code)
  87. {
  88. char *c_str = NULL;
  89. CFErrorRef err = CFErrorCreate(kCFAllocatorDefault,
  90. kCFErrorDomainOSStatus, code, NULL);
  91. CFStringRef str = CFErrorCopyDescription(err);
  92. c_str = cfstr_copy_cstr(str, kCFStringEncodingUTF8);
  93. if (c_str) {
  94. if (enc)
  95. VT_BLOG(log_level, "Error in %s: %s", context, c_str);
  96. else
  97. VT_LOG(log_level, "Error in %s: %s", context, c_str);
  98. }
  99. bfree(c_str);
  100. CFRelease(str);
  101. CFRelease(err);
  102. }
  103. static CFStringRef obs_to_vt_profile(CMVideoCodecType codec_type,
  104. const char *profile,
  105. enum video_format format)
  106. {
  107. if (codec_type == kCMVideoCodecType_H264) {
  108. if (strcmp(profile, "baseline") == 0)
  109. return kVTProfileLevel_H264_Baseline_AutoLevel;
  110. else if (strcmp(profile, "main") == 0)
  111. return kVTProfileLevel_H264_Main_AutoLevel;
  112. else if (strcmp(profile, "high") == 0)
  113. return kVTProfileLevel_H264_High_AutoLevel;
  114. else
  115. return kVTProfileLevel_H264_Main_AutoLevel;
  116. #ifdef ENABLE_HEVC
  117. } else if (codec_type == kCMVideoCodecType_HEVC) {
  118. if (strcmp(profile, "main") == 0) {
  119. if (format == VIDEO_FORMAT_P010) {
  120. VT_LOG(LOG_WARNING, "Forcing main10 for P010");
  121. return kVTProfileLevel_HEVC_Main10_AutoLevel;
  122. } else {
  123. return kVTProfileLevel_HEVC_Main_AutoLevel;
  124. }
  125. }
  126. if (strcmp(profile, "main10") == 0)
  127. return kVTProfileLevel_HEVC_Main10_AutoLevel;
  128. #if __MAC_OS_X_VERSION_MAX_ALLOWED >= 120300 // macOS 12.3
  129. if (__builtin_available(macOS 12.3, *)) {
  130. if (strcmp(profile, "main42210") == 0)
  131. return kVTProfileLevel_HEVC_Main42210_AutoLevel;
  132. }
  133. #endif // macOS 12.3
  134. return kVTProfileLevel_HEVC_Main_AutoLevel;
  135. #else
  136. (void)format;
  137. #endif // ENABLE_HEVC
  138. } else {
  139. return kVTProfileLevel_H264_Baseline_AutoLevel;
  140. }
  141. }
  142. static CFStringRef obs_to_vt_colorspace(enum video_colorspace cs)
  143. {
  144. switch (cs) {
  145. case VIDEO_CS_601:
  146. return kCVImageBufferYCbCrMatrix_ITU_R_601_4;
  147. case VIDEO_CS_2100_PQ:
  148. case VIDEO_CS_2100_HLG:
  149. return kCVImageBufferYCbCrMatrix_ITU_R_2020;
  150. default:
  151. return kCVImageBufferYCbCrMatrix_ITU_R_709_2;
  152. }
  153. }
  154. static CFStringRef obs_to_vt_primaries(enum video_colorspace cs)
  155. {
  156. switch (cs) {
  157. case VIDEO_CS_601:
  158. return kCVImageBufferColorPrimaries_SMPTE_C;
  159. case VIDEO_CS_2100_PQ:
  160. case VIDEO_CS_2100_HLG:
  161. return kCVImageBufferColorPrimaries_ITU_R_2020;
  162. default:
  163. return kCVImageBufferColorPrimaries_ITU_R_709_2;
  164. }
  165. }
  166. static CFStringRef obs_to_vt_transfer(enum video_colorspace cs)
  167. {
  168. switch (cs) {
  169. case VIDEO_CS_SRGB:
  170. return kCVImageBufferTransferFunction_sRGB;
  171. case VIDEO_CS_2100_PQ:
  172. return kCVImageBufferTransferFunction_SMPTE_ST_2084_PQ;
  173. case VIDEO_CS_2100_HLG:
  174. return kCVImageBufferTransferFunction_ITU_R_2100_HLG;
  175. default:
  176. return kCVImageBufferTransferFunction_ITU_R_709_2;
  177. }
  178. }
  179. /* Adapted from Chromium GenerateMasteringDisplayColorVolume */
  180. static CFDataRef obs_to_vt_masteringdisplay(uint32_t hdr_nominal_peak_level)
  181. {
  182. struct mastering_display_colour_volume {
  183. uint16_t display_primaries[3][2];
  184. uint16_t white_point[2];
  185. uint32_t max_display_mastering_luminance;
  186. uint32_t min_display_mastering_luminance;
  187. };
  188. static_assert(sizeof(struct mastering_display_colour_volume) == 24,
  189. "May need to adjust struct packing");
  190. struct mastering_display_colour_volume mdcv;
  191. mdcv.display_primaries[0][0] = __builtin_bswap16(13250);
  192. mdcv.display_primaries[0][1] = __builtin_bswap16(34500);
  193. mdcv.display_primaries[1][0] = __builtin_bswap16(7500);
  194. mdcv.display_primaries[1][1] = __builtin_bswap16(3000);
  195. mdcv.display_primaries[2][0] = __builtin_bswap16(34000);
  196. mdcv.display_primaries[2][1] = __builtin_bswap16(16000);
  197. mdcv.white_point[0] = __builtin_bswap16(15635);
  198. mdcv.white_point[1] = __builtin_bswap16(16450);
  199. mdcv.max_display_mastering_luminance =
  200. __builtin_bswap32(hdr_nominal_peak_level * 10000);
  201. mdcv.min_display_mastering_luminance = 0;
  202. UInt8 bytes[sizeof(struct mastering_display_colour_volume)];
  203. memcpy(bytes, &mdcv, sizeof(bytes));
  204. return CFDataCreate(kCFAllocatorDefault, bytes, sizeof(bytes));
  205. }
  206. /* Adapted from Chromium GenerateContentLightLevelInfo */
  207. static CFDataRef
  208. obs_to_vt_contentlightlevelinfo(uint16_t hdr_nominal_peak_level)
  209. {
  210. struct content_light_level_info {
  211. uint16_t max_content_light_level;
  212. uint16_t max_pic_average_light_level;
  213. };
  214. static_assert(sizeof(struct content_light_level_info) == 4,
  215. "May need to adjust struct packing");
  216. struct content_light_level_info clli;
  217. clli.max_content_light_level =
  218. __builtin_bswap16(hdr_nominal_peak_level);
  219. clli.max_pic_average_light_level =
  220. __builtin_bswap16(hdr_nominal_peak_level);
  221. UInt8 bytes[sizeof(struct content_light_level_info)];
  222. memcpy(bytes, &clli, sizeof(bytes));
  223. return CFDataCreate(kCFAllocatorDefault, bytes, sizeof(bytes));
  224. }
  225. static OSStatus session_set_prop_float(VTCompressionSessionRef session,
  226. CFStringRef key, float val)
  227. {
  228. CFNumberRef n = CFNumberCreate(NULL, kCFNumberFloat32Type, &val);
  229. OSStatus code = VTSessionSetProperty(session, key, n);
  230. CFRelease(n);
  231. return code;
  232. }
  233. static OSStatus session_set_prop_int(VTCompressionSessionRef session,
  234. CFStringRef key, int32_t val)
  235. {
  236. CFNumberRef n = CFNumberCreate(NULL, kCFNumberSInt32Type, &val);
  237. OSStatus code = VTSessionSetProperty(session, key, n);
  238. CFRelease(n);
  239. return code;
  240. }
  241. static OSStatus session_set_prop_str(VTCompressionSessionRef session,
  242. CFStringRef key, char *val)
  243. {
  244. CFStringRef s = CFStringCreateWithFileSystemRepresentation(NULL, val);
  245. OSStatus code = VTSessionSetProperty(session, key, s);
  246. CFRelease(s);
  247. return code;
  248. }
  249. static OSStatus session_set_prop(VTCompressionSessionRef session,
  250. CFStringRef key, CFTypeRef val)
  251. {
  252. return VTSessionSetProperty(session, key, val);
  253. }
  254. static OSStatus session_set_bitrate(VTCompressionSessionRef session,
  255. const char *rate_control, int new_bitrate,
  256. float quality, bool limit_bitrate,
  257. int max_bitrate, double max_bitrate_window)
  258. {
  259. OSStatus code;
  260. bool can_limit_bitrate;
  261. CFStringRef compressionPropertyKey;
  262. if (strcmp(rate_control, "CBR") == 0) {
  263. compressionPropertyKey =
  264. kVTCompressionPropertyKey_AverageBitRate;
  265. can_limit_bitrate = true;
  266. if (__builtin_available(macOS 13.0, *)) {
  267. #if __MAC_OS_X_VERSION_MAX_ALLOWED >= 130000
  268. if (is_apple_silicon) {
  269. compressionPropertyKey =
  270. kVTCompressionPropertyKey_ConstantBitRate;
  271. can_limit_bitrate = false;
  272. } else {
  273. VT_LOG(LOG_WARNING,
  274. "CBR support for VideoToolbox encoder requires Apple Silicon. "
  275. "Will use ABR instead.");
  276. }
  277. #else
  278. VT_LOG(LOG_WARNING,
  279. "CBR support for VideoToolbox not available in this build of OBS. "
  280. "Will use ABR instead.");
  281. #endif
  282. } else {
  283. VT_LOG(LOG_WARNING,
  284. "CBR support for VideoToolbox encoder requires macOS 13 or newer. "
  285. "Will use ABR instead.");
  286. }
  287. } else if (strcmp(rate_control, "ABR") == 0) {
  288. compressionPropertyKey =
  289. kVTCompressionPropertyKey_AverageBitRate;
  290. can_limit_bitrate = true;
  291. } else if (strcmp(rate_control, "CRF") == 0) {
  292. if (is_apple_silicon) {
  293. compressionPropertyKey =
  294. kVTCompressionPropertyKey_Quality;
  295. code = session_set_prop_float(
  296. session, compressionPropertyKey, quality);
  297. if (code != noErr) {
  298. return code;
  299. }
  300. } else {
  301. VT_LOG(LOG_WARNING,
  302. "CRF support for VideoToolbox encoder requires Apple Silicon. "
  303. "Will use ABR instead.");
  304. compressionPropertyKey =
  305. kVTCompressionPropertyKey_AverageBitRate;
  306. }
  307. can_limit_bitrate = true;
  308. } else {
  309. VT_LOG(LOG_ERROR,
  310. "Selected rate control method is not supported: %s",
  311. rate_control);
  312. return kVTParameterErr;
  313. }
  314. if (compressionPropertyKey != kVTCompressionPropertyKey_Quality) {
  315. code = session_set_prop_int(session, compressionPropertyKey,
  316. new_bitrate * 1000);
  317. if (code != noErr) {
  318. return code;
  319. }
  320. }
  321. if (limit_bitrate && can_limit_bitrate) {
  322. double cpb_size = max_bitrate * 125 * max_bitrate_window;
  323. CFNumberRef cf_cpb_size = CFNumberCreate(
  324. kCFAllocatorDefault, kCFNumberIntType, &cpb_size);
  325. CFNumberRef cf_cpb_window_size =
  326. CFNumberCreate(kCFAllocatorDefault, kCFNumberFloatType,
  327. &max_bitrate_window);
  328. CFTypeRef values[2] = {cf_cpb_size, cf_cpb_window_size};
  329. CFArrayRef rate_control_data = CFArrayCreate(
  330. kCFAllocatorDefault, values, 2, &kCFTypeArrayCallBacks);
  331. code = session_set_prop(
  332. session, kVTCompressionPropertyKey_DataRateLimits,
  333. rate_control_data);
  334. CFRelease(cf_cpb_size);
  335. CFRelease(cf_cpb_window_size);
  336. CFRelease(rate_control_data);
  337. if (code == kVTPropertyNotSupportedErr) {
  338. log_osstatus(LOG_WARNING, NULL,
  339. "setting DataRateLimits on session", code);
  340. return noErr;
  341. }
  342. }
  343. return noErr;
  344. }
  345. static OSStatus session_set_colorspace(VTCompressionSessionRef session,
  346. enum video_colorspace cs)
  347. {
  348. OSStatus code;
  349. CFTypeRef keys[5] = {kVTCompressionPropertyKey_ColorPrimaries,
  350. kVTCompressionPropertyKey_TransferFunction,
  351. kVTCompressionPropertyKey_YCbCrMatrix, NULL, NULL};
  352. CFTypeRef values[5] = {obs_to_vt_primaries(cs), obs_to_vt_transfer(cs),
  353. obs_to_vt_colorspace(cs), NULL, NULL};
  354. CFDataRef masteringDisplayColorVolume = NULL;
  355. CFDataRef contentLightLevel = NULL;
  356. if (cs == VIDEO_CS_2100_PQ) {
  357. const uint16_t hdr_nominal_peak_level =
  358. (uint16_t)obs_get_video_hdr_nominal_peak_level();
  359. masteringDisplayColorVolume =
  360. obs_to_vt_masteringdisplay(hdr_nominal_peak_level);
  361. contentLightLevel =
  362. obs_to_vt_contentlightlevelinfo(hdr_nominal_peak_level);
  363. keys[3] = kVTCompressionPropertyKey_MasteringDisplayColorVolume;
  364. keys[4] = kVTCompressionPropertyKey_ContentLightLevelInfo;
  365. values[3] = masteringDisplayColorVolume;
  366. values[4] = contentLightLevel;
  367. } else if (cs == VIDEO_CS_2100_HLG) {
  368. masteringDisplayColorVolume = obs_to_vt_masteringdisplay(1000);
  369. contentLightLevel = obs_to_vt_contentlightlevelinfo(1000);
  370. keys[3] = kVTCompressionPropertyKey_MasteringDisplayColorVolume;
  371. keys[4] = kVTCompressionPropertyKey_ContentLightLevelInfo;
  372. values[3] = masteringDisplayColorVolume;
  373. values[4] = contentLightLevel;
  374. }
  375. CFDictionaryRef session_properties =
  376. CFDictionaryCreate(kCFAllocatorDefault, keys, values, 5,
  377. &kCFTypeDictionaryKeyCallBacks,
  378. &kCFTypeDictionaryValueCallBacks);
  379. code = VTSessionSetProperties(session, session_properties);
  380. CFRelease(session_properties);
  381. if (masteringDisplayColorVolume != NULL) {
  382. CFRelease(masteringDisplayColorVolume);
  383. }
  384. if (contentLightLevel != NULL) {
  385. CFRelease(contentLightLevel);
  386. }
  387. return code;
  388. }
  389. void sample_encoded_callback(void *data, void *source, OSStatus status,
  390. VTEncodeInfoFlags info_flags,
  391. CMSampleBufferRef buffer)
  392. {
  393. if (status != noErr) {
  394. log_osstatus(LOG_ERROR, NULL, "encoder callback", status);
  395. return;
  396. }
  397. if (info_flags == kVTEncodeInfo_FrameDropped) {
  398. VT_LOG(LOG_INFO, "Frame dropped by encoder");
  399. }
  400. CMSimpleQueueRef queue = data;
  401. CVPixelBufferRef pixbuf = source;
  402. if (buffer != NULL) {
  403. CFRetain(buffer);
  404. CMSimpleQueueEnqueue(queue, buffer);
  405. }
  406. CFRelease(pixbuf);
  407. }
  408. static inline CFDictionaryRef create_encoder_spec(const char *vt_encoder_id)
  409. {
  410. CFStringRef id =
  411. CFStringCreateWithFileSystemRepresentation(NULL, vt_encoder_id);
  412. CFTypeRef keys[1] = {kVTVideoEncoderSpecification_EncoderID};
  413. CFTypeRef values[1] = {id};
  414. CFDictionaryRef encoder_spec =
  415. CFDictionaryCreate(kCFAllocatorDefault, keys, values, 1,
  416. &kCFTypeDictionaryKeyCallBacks,
  417. &kCFTypeDictionaryValueCallBacks);
  418. CFRelease(id);
  419. return encoder_spec;
  420. }
  421. static inline CFDictionaryRef
  422. create_prores_encoder_spec(CMVideoCodecType target_codec_type,
  423. bool hardware_accelerated)
  424. {
  425. CFStringRef encoder_id = NULL;
  426. size_t size = 0;
  427. struct vt_prores_encoder_data *encoder_list = NULL;
  428. if (hardware_accelerated) {
  429. size = vt_prores_hardware_encoder_list.num;
  430. encoder_list = vt_prores_hardware_encoder_list.array;
  431. } else {
  432. size = vt_prores_software_encoder_list.num;
  433. encoder_list = vt_prores_software_encoder_list.array;
  434. }
  435. for (size_t i = 0; i < size; ++i) {
  436. if (target_codec_type == encoder_list[i].codec_type) {
  437. encoder_id = encoder_list[i].encoder_id;
  438. }
  439. }
  440. CFTypeRef keys[1] = {kVTVideoEncoderSpecification_EncoderID};
  441. CFTypeRef values[1] = {encoder_id};
  442. CFDictionaryRef encoder_spec =
  443. CFDictionaryCreate(kCFAllocatorDefault, keys, values, 1,
  444. &kCFTypeDictionaryKeyCallBacks,
  445. &kCFTypeDictionaryValueCallBacks);
  446. return encoder_spec;
  447. }
  448. static inline CFDictionaryRef create_pixbuf_spec(struct vt_encoder *enc)
  449. {
  450. CFNumberRef PixelFormat = CFNumberCreate(
  451. kCFAllocatorDefault, kCFNumberSInt32Type, &enc->vt_pix_fmt);
  452. CFNumberRef Width = CFNumberCreate(kCFAllocatorDefault,
  453. kCFNumberSInt32Type, &enc->width);
  454. CFNumberRef Height = CFNumberCreate(kCFAllocatorDefault,
  455. kCFNumberSInt32Type, &enc->height);
  456. CFTypeRef keys[3] = {kCVPixelBufferPixelFormatTypeKey,
  457. kCVPixelBufferWidthKey, kCVPixelBufferHeightKey};
  458. CFTypeRef values[3] = {PixelFormat, Width, Height};
  459. CFDictionaryRef pixbuf_spec =
  460. CFDictionaryCreate(kCFAllocatorDefault, keys, values, 3,
  461. &kCFTypeDictionaryKeyCallBacks,
  462. &kCFTypeDictionaryValueCallBacks);
  463. CFRelease(PixelFormat);
  464. CFRelease(Width);
  465. CFRelease(Height);
  466. return pixbuf_spec;
  467. }
  468. static bool create_encoder(struct vt_encoder *enc)
  469. {
  470. OSStatus code;
  471. VTCompressionSessionRef s;
  472. const char *codec_name = obs_encoder_get_codec(enc->encoder);
  473. CFDictionaryRef encoder_spec;
  474. if (strcmp(codec_name, "prores") == 0) {
  475. struct vt_encoder_type_data *type_data =
  476. (struct vt_encoder_type_data *)
  477. obs_encoder_get_type_data(enc->encoder);
  478. encoder_spec = create_prores_encoder_spec(
  479. enc->codec_type, type_data->hardware_accelerated);
  480. } else {
  481. encoder_spec = create_encoder_spec(enc->vt_encoder_id);
  482. }
  483. CFDictionaryRef pixbuf_spec = create_pixbuf_spec(enc);
  484. code = VTCompressionSessionCreate(kCFAllocatorDefault, enc->width,
  485. enc->height, enc->codec_type,
  486. encoder_spec, pixbuf_spec, NULL,
  487. &sample_encoded_callback, enc->queue,
  488. &s);
  489. if (code != noErr) {
  490. log_osstatus(LOG_ERROR, enc, "VTCompressionSessionCreate",
  491. code);
  492. }
  493. CFRelease(encoder_spec);
  494. CFRelease(pixbuf_spec);
  495. CFBooleanRef b = NULL;
  496. code = VTSessionCopyProperty(
  497. s,
  498. kVTCompressionPropertyKey_UsingHardwareAcceleratedVideoEncoder,
  499. NULL, &b);
  500. if (code == noErr && (enc->hw_enc = CFBooleanGetValue(b)))
  501. VT_BLOG(LOG_INFO, "session created with hardware encoding");
  502. else
  503. enc->hw_enc = false;
  504. if (b != NULL)
  505. CFRelease(b);
  506. if (enc->codec_type == kCMVideoCodecType_H264 ||
  507. enc->codec_type == kCMVideoCodecType_HEVC) {
  508. /* Apple's documentation states that a keyframe interval of 0 will result in
  509. * the encoder automatically picking times to insert them; However, Apple's
  510. * encoder, when in CRF mode, will never actually insert any keyframes past
  511. * the very first one, rendering the files near-unusable in editors or
  512. * video players. So to avoid that happening, enforce a reasonable default
  513. * of 10 seconds in CRF mode. */
  514. if (enc->keyint == 0 && strcmp(enc->rate_control, "CRF") == 0) {
  515. VT_BLOG(LOG_INFO,
  516. "Enforcing non-zero keyframe interval in CRF mode");
  517. enc->keyint = 10;
  518. }
  519. // This can fail when using GPU hardware encoding
  520. code = session_set_prop_int(
  521. s,
  522. kVTCompressionPropertyKey_MaxKeyFrameIntervalDuration,
  523. enc->keyint);
  524. if (code != noErr)
  525. log_osstatus(
  526. LOG_WARNING, enc,
  527. "setting kVTCompressionPropertyKey_MaxKeyFrameIntervalDuration failed, "
  528. "keyframe interval might be incorrect",
  529. code);
  530. CFTypeRef session_keys[4] = {
  531. kVTCompressionPropertyKey_MaxKeyFrameInterval,
  532. kVTCompressionPropertyKey_ExpectedFrameRate,
  533. kVTCompressionPropertyKey_AllowFrameReordering,
  534. kVTCompressionPropertyKey_ProfileLevel};
  535. float key_frame_interval =
  536. enc->keyint * ((float)enc->fps_num / enc->fps_den);
  537. float expected_framerate = (float)enc->fps_num / enc->fps_den;
  538. CFNumberRef MaxKeyFrameInterval =
  539. CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type,
  540. &key_frame_interval);
  541. CFNumberRef ExpectedFrameRate = CFNumberCreate(
  542. kCFAllocatorDefault, kCFNumberFloat32Type,
  543. &expected_framerate);
  544. CFTypeRef AllowFrameReordering = enc->bframes ? kCFBooleanTrue
  545. : kCFBooleanFalse;
  546. video_t *video = obs_encoder_video(enc->encoder);
  547. const struct video_output_info *voi =
  548. video_output_get_info(video);
  549. CFTypeRef ProfileLevel = obs_to_vt_profile(
  550. enc->codec_type, enc->profile, voi->format);
  551. CFTypeRef session_values[4] = {MaxKeyFrameInterval,
  552. ExpectedFrameRate,
  553. AllowFrameReordering,
  554. ProfileLevel};
  555. CFDictionaryRef session_properties = CFDictionaryCreate(
  556. kCFAllocatorDefault, session_keys, session_values, 4,
  557. &kCFTypeDictionaryKeyCallBacks,
  558. &kCFTypeDictionaryValueCallBacks);
  559. code = VTSessionSetProperties(s, session_properties);
  560. CFRelease(MaxKeyFrameInterval);
  561. CFRelease(ExpectedFrameRate);
  562. CFRelease(AllowFrameReordering);
  563. CFRelease(ProfileLevel);
  564. CFRelease(session_properties);
  565. if (code != noErr) {
  566. return code;
  567. }
  568. code = session_set_bitrate(s, enc->rate_control, enc->bitrate,
  569. enc->quality, enc->limit_bitrate,
  570. enc->rc_max_bitrate,
  571. enc->rc_max_bitrate_window);
  572. if (code != noErr) {
  573. return code;
  574. }
  575. }
  576. // This can fail depending on hardware configuration
  577. code = session_set_prop(s, kVTCompressionPropertyKey_RealTime,
  578. kCFBooleanFalse);
  579. if (code != noErr)
  580. log_osstatus(
  581. LOG_WARNING, enc,
  582. "setting kVTCompressionPropertyKey_RealTime failed, "
  583. "frame delay might be increased",
  584. code);
  585. code = session_set_colorspace(s, enc->colorspace);
  586. if (code != noErr) {
  587. return code;
  588. }
  589. code = VTCompressionSessionPrepareToEncodeFrames(s);
  590. if (code != noErr) {
  591. return code;
  592. }
  593. enc->session = s;
  594. return true;
  595. fail:
  596. if (encoder_spec != NULL)
  597. CFRelease(encoder_spec);
  598. if (pixbuf_spec != NULL)
  599. CFRelease(pixbuf_spec);
  600. return false;
  601. }
  602. static void vt_destroy(void *data)
  603. {
  604. struct vt_encoder *enc = data;
  605. if (enc) {
  606. if (enc->session != NULL) {
  607. VTCompressionSessionInvalidate(enc->session);
  608. CFRelease(enc->session);
  609. }
  610. da_free(enc->packet_data);
  611. da_free(enc->extra_data);
  612. bfree(enc);
  613. }
  614. }
  615. static void dump_encoder_info(struct vt_encoder *enc)
  616. {
  617. VT_BLOG(LOG_INFO,
  618. "settings:\n"
  619. "\tvt_encoder_id %s\n"
  620. "\trate_control: %s\n"
  621. "\tbitrate: %d (kbps)\n"
  622. "\tquality: %f\n"
  623. "\tfps_num: %d\n"
  624. "\tfps_den: %d\n"
  625. "\twidth: %d\n"
  626. "\theight: %d\n"
  627. "\tkeyint: %d (s)\n"
  628. "\tlimit_bitrate: %s\n"
  629. "\trc_max_bitrate: %d (kbps)\n"
  630. "\trc_max_bitrate_window: %f (s)\n"
  631. "\thw_enc: %s\n"
  632. "\tprofile: %s\n"
  633. "\tcodec_type: %.4s\n",
  634. enc->vt_encoder_id, enc->rate_control, enc->bitrate,
  635. enc->quality, enc->fps_num, enc->fps_den, enc->width,
  636. enc->height, enc->keyint, enc->limit_bitrate ? "on" : "off",
  637. enc->rc_max_bitrate, enc->rc_max_bitrate_window,
  638. enc->hw_enc ? "on" : "off",
  639. (enc->profile != NULL && !!strlen(enc->profile)) ? enc->profile
  640. : "default",
  641. codec_type_to_print_fmt(enc->codec_type));
  642. }
  643. typedef enum {
  644. kResultSuccess = 0,
  645. kResultColorFormatUnsupported = 1,
  646. kResultFullRangeUnsupported = 2,
  647. } SetVideoFormatResult;
  648. static SetVideoFormatResult set_video_format(struct vt_encoder *enc,
  649. enum video_format format,
  650. enum video_range_type range)
  651. {
  652. bool full_range = range == VIDEO_RANGE_FULL;
  653. switch (format) {
  654. case VIDEO_FORMAT_I420:
  655. enc->vt_pix_fmt =
  656. full_range
  657. ? kCVPixelFormatType_420YpCbCr8PlanarFullRange
  658. : kCVPixelFormatType_420YpCbCr8Planar;
  659. return kResultSuccess;
  660. case VIDEO_FORMAT_NV12:
  661. enc->vt_pix_fmt =
  662. full_range
  663. ? kCVPixelFormatType_420YpCbCr8BiPlanarFullRange
  664. : kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange;
  665. return kResultSuccess;
  666. case VIDEO_FORMAT_P010:
  667. if (enc->codec_type == kCMVideoCodecType_HEVC) {
  668. enc->vt_pix_fmt =
  669. full_range
  670. ? kCVPixelFormatType_420YpCbCr10BiPlanarFullRange
  671. : kCVPixelFormatType_420YpCbCr10BiPlanarVideoRange;
  672. return kResultSuccess;
  673. }
  674. break;
  675. case VIDEO_FORMAT_P216:
  676. if (!full_range) {
  677. enc->vt_pix_fmt =
  678. kCVPixelFormatType_422YpCbCr16BiPlanarVideoRange;
  679. return kResultSuccess;
  680. } else {
  681. return kResultFullRangeUnsupported;
  682. }
  683. break;
  684. case VIDEO_FORMAT_P416:
  685. if (!full_range) {
  686. enc->vt_pix_fmt =
  687. kCVPixelFormatType_444YpCbCr16BiPlanarVideoRange;
  688. return kResultSuccess;
  689. } else {
  690. return kResultFullRangeUnsupported;
  691. }
  692. break;
  693. default:
  694. return kResultColorFormatUnsupported;
  695. }
  696. return kResultColorFormatUnsupported;
  697. }
  698. static bool update_params(struct vt_encoder *enc, obs_data_t *settings)
  699. {
  700. video_t *video = obs_encoder_video(enc->encoder);
  701. const struct video_output_info *voi = video_output_get_info(video);
  702. const char *codec = obs_encoder_get_codec(enc->encoder);
  703. if (strcmp(codec, "h264") == 0) {
  704. enc->codec_type = kCMVideoCodecType_H264;
  705. obs_data_set_int(settings, "codec_type", enc->codec_type);
  706. #ifdef ENABLE_HEVC
  707. } else if (strcmp(codec, "hevc") == 0) {
  708. enc->codec_type = kCMVideoCodecType_HEVC;
  709. obs_data_set_int(settings, "codec_type", enc->codec_type);
  710. #endif
  711. } else {
  712. enc->codec_type = (CMVideoCodecType)obs_data_get_int(
  713. settings, "codec_type");
  714. }
  715. SetVideoFormatResult res =
  716. set_video_format(enc, voi->format, voi->range);
  717. if (res == kResultColorFormatUnsupported) {
  718. obs_encoder_set_last_error(
  719. enc->encoder,
  720. obs_module_text("ColorFormatUnsupported"));
  721. VT_BLOG(LOG_WARNING, "Unsupported color format selected");
  722. return false;
  723. } else if (res == kResultFullRangeUnsupported) {
  724. obs_encoder_set_last_error(
  725. enc->encoder, obs_module_text("FullRangeUnsupported"));
  726. VT_BLOG(LOG_WARNING, "Unsupported color range (full) selected");
  727. return false;
  728. }
  729. enc->colorspace = voi->colorspace;
  730. enc->width = obs_encoder_get_width(enc->encoder);
  731. enc->height = obs_encoder_get_height(enc->encoder);
  732. enc->fps_num = voi->fps_num;
  733. enc->fps_den = voi->fps_den;
  734. enc->keyint = (uint32_t)obs_data_get_int(settings, "keyint_sec");
  735. enc->rate_control = obs_data_get_string(settings, "rate_control");
  736. enc->bitrate = (uint32_t)obs_data_get_int(settings, "bitrate");
  737. enc->quality = ((float)obs_data_get_int(settings, "quality")) / 100;
  738. enc->profile = obs_data_get_string(settings, "profile");
  739. enc->limit_bitrate = obs_data_get_bool(settings, "limit_bitrate");
  740. enc->rc_max_bitrate =
  741. (uint32_t)obs_data_get_int(settings, "max_bitrate");
  742. enc->rc_max_bitrate_window =
  743. obs_data_get_double(settings, "max_bitrate_window");
  744. enc->bframes = obs_data_get_bool(settings, "bframes");
  745. return true;
  746. }
  747. static bool vt_update(void *data, obs_data_t *settings)
  748. {
  749. struct vt_encoder *enc = data;
  750. uint32_t old_bitrate = enc->bitrate;
  751. bool old_limit_bitrate = enc->limit_bitrate;
  752. update_params(enc, settings);
  753. if (old_bitrate == enc->bitrate &&
  754. old_limit_bitrate == enc->limit_bitrate)
  755. return true;
  756. OSStatus code = session_set_bitrate(enc->session, enc->rate_control,
  757. enc->bitrate, enc->quality,
  758. enc->limit_bitrate,
  759. enc->rc_max_bitrate,
  760. enc->rc_max_bitrate_window);
  761. if (code != noErr)
  762. VT_BLOG(LOG_WARNING, "Failed to set bitrate to session");
  763. dump_encoder_info(enc);
  764. return true;
  765. }
  766. static void *vt_create(obs_data_t *settings, obs_encoder_t *encoder)
  767. {
  768. struct vt_encoder *enc = bzalloc(sizeof(struct vt_encoder));
  769. OSStatus code;
  770. enc->encoder = encoder;
  771. enc->vt_encoder_id = obs_encoder_get_id(encoder);
  772. if (!update_params(enc, settings))
  773. goto fail;
  774. code = CMSimpleQueueCreate(NULL, 100, &enc->queue);
  775. if (code != noErr) {
  776. goto fail;
  777. }
  778. if (!create_encoder(enc))
  779. goto fail;
  780. dump_encoder_info(enc);
  781. return enc;
  782. fail:
  783. vt_destroy(enc);
  784. return NULL;
  785. }
  786. static const uint8_t annexb_startcode[4] = {0, 0, 0, 1};
  787. static void packet_put(struct darray *packet, const uint8_t *buf, size_t size)
  788. {
  789. darray_push_back_array(sizeof(uint8_t), packet, buf, size);
  790. }
  791. static void packet_put_startcode(struct darray *packet, int size)
  792. {
  793. assert(size == 3 || size == 4);
  794. packet_put(packet, &annexb_startcode[4 - size], size);
  795. }
  796. static bool handle_prores_packet(struct vt_encoder *enc,
  797. CMSampleBufferRef buffer)
  798. {
  799. OSStatus err = 0;
  800. size_t block_size = 0;
  801. uint8_t *block_buf = NULL;
  802. CMBlockBufferRef block = CMSampleBufferGetDataBuffer(buffer);
  803. if (block == NULL) {
  804. VT_BLOG(LOG_ERROR,
  805. "Failed to get block buffer for ProRes frame.");
  806. return false;
  807. }
  808. err = CMBlockBufferGetDataPointer(block, 0, NULL, &block_size,
  809. (char **)&block_buf);
  810. if (err != 0) {
  811. VT_BLOG(LOG_ERROR,
  812. "Failed to get data buffer pointer for ProRes frame.");
  813. return false;
  814. }
  815. packet_put(&enc->packet_data.da, block_buf, block_size);
  816. return true;
  817. }
  818. static void convert_block_nals_to_annexb(struct vt_encoder *enc,
  819. struct darray *packet,
  820. CMBlockBufferRef block,
  821. int nal_length_bytes)
  822. {
  823. size_t block_size;
  824. uint8_t *block_buf;
  825. CMBlockBufferGetDataPointer(block, 0, NULL, &block_size,
  826. (char **)&block_buf);
  827. size_t bytes_remaining = block_size;
  828. while (bytes_remaining > 0) {
  829. uint32_t nal_size;
  830. if (nal_length_bytes == 1)
  831. nal_size = block_buf[0];
  832. else if (nal_length_bytes == 2)
  833. nal_size = CFSwapInt16BigToHost(
  834. ((uint16_t *)block_buf)[0]);
  835. else if (nal_length_bytes == 4)
  836. nal_size = CFSwapInt32BigToHost(
  837. ((uint32_t *)block_buf)[0]);
  838. else
  839. return;
  840. bytes_remaining -= nal_length_bytes;
  841. block_buf += nal_length_bytes;
  842. if (bytes_remaining < nal_size) {
  843. VT_BLOG(LOG_ERROR, "invalid nal block");
  844. return;
  845. }
  846. packet_put_startcode(packet, 3);
  847. packet_put(packet, block_buf, nal_size);
  848. bytes_remaining -= nal_size;
  849. block_buf += nal_size;
  850. }
  851. }
  852. static bool handle_keyframe(struct vt_encoder *enc,
  853. CMFormatDescriptionRef format_desc,
  854. size_t param_count, struct darray *packet,
  855. struct darray *extra_data)
  856. {
  857. OSStatus code;
  858. const uint8_t *param;
  859. size_t param_size;
  860. for (size_t i = 0; i < param_count; i++) {
  861. if (enc->codec_type == kCMVideoCodecType_H264) {
  862. code = CMVideoFormatDescriptionGetH264ParameterSetAtIndex(
  863. format_desc, i, &param, &param_size, NULL,
  864. NULL);
  865. #ifdef ENABLE_HEVC
  866. } else if (enc->codec_type == kCMVideoCodecType_HEVC) {
  867. code = CMVideoFormatDescriptionGetHEVCParameterSetAtIndex(
  868. format_desc, i, &param, &param_size, NULL,
  869. NULL);
  870. #endif
  871. }
  872. if (code != noErr) {
  873. log_osstatus(LOG_ERROR, enc,
  874. "getting NAL parameter "
  875. "at index",
  876. code);
  877. return false;
  878. }
  879. packet_put_startcode(packet, 4);
  880. packet_put(packet, param, param_size);
  881. }
  882. // if we were passed an extra_data array, fill it with
  883. // SPS, PPS, etc.
  884. if (extra_data != NULL)
  885. packet_put(extra_data, packet->array, packet->num);
  886. return true;
  887. }
  888. static bool convert_sample_to_annexb(struct vt_encoder *enc,
  889. struct darray *packet,
  890. struct darray *extra_data,
  891. CMSampleBufferRef buffer, bool keyframe)
  892. {
  893. OSStatus code;
  894. CMFormatDescriptionRef format_desc =
  895. CMSampleBufferGetFormatDescription(buffer);
  896. size_t param_count;
  897. int nal_length_bytes;
  898. if (enc->codec_type == kCMVideoCodecType_H264) {
  899. code = CMVideoFormatDescriptionGetH264ParameterSetAtIndex(
  900. format_desc, 0, NULL, NULL, &param_count,
  901. &nal_length_bytes);
  902. #ifdef ENABLE_HEVC
  903. } else if (enc->codec_type == kCMVideoCodecType_HEVC) {
  904. code = CMVideoFormatDescriptionGetHEVCParameterSetAtIndex(
  905. format_desc, 0, NULL, NULL, &param_count,
  906. &nal_length_bytes);
  907. #endif
  908. }
  909. // it is not clear what errors this function can return
  910. // so we check the two most reasonable
  911. if (code == kCMFormatDescriptionBridgeError_InvalidParameter ||
  912. code == kCMFormatDescriptionError_InvalidParameter) {
  913. VT_BLOG(LOG_WARNING, "assuming 2 parameter sets "
  914. "and 4 byte NAL length header");
  915. param_count = 2;
  916. nal_length_bytes = 4;
  917. } else if (code != noErr) {
  918. log_osstatus(LOG_ERROR, enc,
  919. "getting parameter count from sample", code);
  920. return false;
  921. }
  922. if (keyframe &&
  923. !handle_keyframe(enc, format_desc, param_count, packet, extra_data))
  924. return false;
  925. CMBlockBufferRef block = CMSampleBufferGetDataBuffer(buffer);
  926. convert_block_nals_to_annexb(enc, packet, block, nal_length_bytes);
  927. return true;
  928. }
  929. static bool is_sample_keyframe(CMSampleBufferRef buffer)
  930. {
  931. CFArrayRef attachments =
  932. CMSampleBufferGetSampleAttachmentsArray(buffer, false);
  933. if (attachments != NULL) {
  934. CFDictionaryRef attachment;
  935. CFBooleanRef has_dependencies;
  936. attachment =
  937. (CFDictionaryRef)CFArrayGetValueAtIndex(attachments, 0);
  938. has_dependencies = (CFBooleanRef)CFDictionaryGetValue(
  939. attachment, kCMSampleAttachmentKey_DependsOnOthers);
  940. return has_dependencies == kCFBooleanFalse;
  941. }
  942. return false;
  943. }
  944. static bool parse_sample(struct vt_encoder *enc, CMSampleBufferRef buffer,
  945. struct encoder_packet *packet, CMTime off)
  946. {
  947. CMTime pts = CMSampleBufferGetPresentationTimeStamp(buffer);
  948. CMTime dts = CMSampleBufferGetDecodeTimeStamp(buffer);
  949. if (CMTIME_IS_INVALID(dts))
  950. dts = pts;
  951. // imitate x264's negative dts when bframes might have pts < dts
  952. else if (enc->bframes)
  953. dts = CMTimeSubtract(dts, off);
  954. pts = CMTimeMultiply(pts, enc->fps_num);
  955. dts = CMTimeMultiply(dts, enc->fps_num);
  956. const bool is_avc = enc->codec_type == kCMVideoCodecType_H264;
  957. const bool has_annexb = is_avc ||
  958. (enc->codec_type == kCMVideoCodecType_HEVC);
  959. // All ProRes frames are "keyframes"
  960. const bool keyframe = !has_annexb || is_sample_keyframe(buffer);
  961. da_resize(enc->packet_data, 0);
  962. // If we are still looking for extra data
  963. struct darray *extra_data = NULL;
  964. if (enc->extra_data.num == 0)
  965. extra_data = &enc->extra_data.da;
  966. if (has_annexb) {
  967. if (!convert_sample_to_annexb(enc, &enc->packet_data.da,
  968. extra_data, buffer, keyframe))
  969. goto fail;
  970. } else {
  971. if (!handle_prores_packet(enc, buffer))
  972. goto fail;
  973. }
  974. packet->type = OBS_ENCODER_VIDEO;
  975. packet->pts = (int64_t)(CMTimeGetSeconds(pts));
  976. packet->dts = (int64_t)(CMTimeGetSeconds(dts));
  977. packet->data = enc->packet_data.array;
  978. packet->size = enc->packet_data.num;
  979. packet->keyframe = keyframe;
  980. if (is_avc) {
  981. // VideoToolbox produces packets with priority lower than the RTMP code
  982. // expects, which causes it to be unable to recover from frame drops.
  983. // Fix this by manually adjusting the priority.
  984. uint8_t *start = enc->packet_data.array;
  985. uint8_t *end = start + enc->packet_data.num;
  986. start = (uint8_t *)obs_avc_find_startcode(start, end);
  987. while (true) {
  988. while (start < end && !*(start++))
  989. ;
  990. if (start == end)
  991. break;
  992. const int type = start[0] & 0x1F;
  993. if (type == OBS_NAL_SLICE_IDR ||
  994. type == OBS_NAL_SLICE) {
  995. uint8_t prev_type = (start[0] >> 5) & 0x3;
  996. start[0] &= ~(3 << 5);
  997. if (type == OBS_NAL_SLICE_IDR)
  998. start[0] |= OBS_NAL_PRIORITY_HIGHEST
  999. << 5;
  1000. else if (type == OBS_NAL_SLICE &&
  1001. prev_type !=
  1002. OBS_NAL_PRIORITY_DISPOSABLE)
  1003. start[0] |= OBS_NAL_PRIORITY_HIGH << 5;
  1004. else
  1005. start[0] |= prev_type << 5;
  1006. }
  1007. start = (uint8_t *)obs_avc_find_startcode(start, end);
  1008. }
  1009. }
  1010. CFRelease(buffer);
  1011. return true;
  1012. fail:
  1013. CFRelease(buffer);
  1014. return false;
  1015. }
  1016. bool get_cached_pixel_buffer(struct vt_encoder *enc, CVPixelBufferRef *buf)
  1017. {
  1018. OSStatus code;
  1019. CVPixelBufferPoolRef pool =
  1020. VTCompressionSessionGetPixelBufferPool(enc->session);
  1021. if (!pool)
  1022. return kCVReturnError;
  1023. CVPixelBufferRef pixbuf;
  1024. code = CVPixelBufferPoolCreatePixelBuffer(NULL, pool, &pixbuf);
  1025. if (code != noErr) {
  1026. goto fail;
  1027. }
  1028. // Why aren't these already set on the pixel buffer?
  1029. // I would have expected pixel buffers from the session's
  1030. // pool to have the correct color space stuff set
  1031. const enum video_colorspace cs = enc->colorspace;
  1032. CVBufferSetAttachment(pixbuf, kCVImageBufferYCbCrMatrixKey,
  1033. obs_to_vt_colorspace(cs),
  1034. kCVAttachmentMode_ShouldPropagate);
  1035. CVBufferSetAttachment(pixbuf, kCVImageBufferColorPrimariesKey,
  1036. obs_to_vt_primaries(cs),
  1037. kCVAttachmentMode_ShouldPropagate);
  1038. CVBufferSetAttachment(pixbuf, kCVImageBufferTransferFunctionKey,
  1039. obs_to_vt_transfer(cs),
  1040. kCVAttachmentMode_ShouldPropagate);
  1041. const bool pq = cs == VIDEO_CS_2100_PQ;
  1042. const bool hlg = cs == VIDEO_CS_2100_HLG;
  1043. if (pq || hlg) {
  1044. const uint16_t hdr_nominal_peak_level =
  1045. pq ? (uint16_t)obs_get_video_hdr_nominal_peak_level()
  1046. : (hlg ? 1000 : 0);
  1047. CFDataRef masteringDisplayColorVolume =
  1048. obs_to_vt_masteringdisplay(hdr_nominal_peak_level);
  1049. CFDataRef contentLightLevel =
  1050. obs_to_vt_contentlightlevelinfo(hdr_nominal_peak_level);
  1051. CVBufferSetAttachment(
  1052. pixbuf, kCVImageBufferMasteringDisplayColorVolumeKey,
  1053. masteringDisplayColorVolume,
  1054. kCVAttachmentMode_ShouldPropagate);
  1055. CVBufferSetAttachment(pixbuf,
  1056. kCVImageBufferContentLightLevelInfoKey,
  1057. contentLightLevel,
  1058. kCVAttachmentMode_ShouldPropagate);
  1059. CFRelease(masteringDisplayColorVolume);
  1060. CFRelease(contentLightLevel);
  1061. }
  1062. *buf = pixbuf;
  1063. return true;
  1064. fail:
  1065. return false;
  1066. }
  1067. static bool vt_encode(void *data, struct encoder_frame *frame,
  1068. struct encoder_packet *packet, bool *received_packet)
  1069. {
  1070. struct vt_encoder *enc = data;
  1071. OSStatus code;
  1072. CMTime dur = CMTimeMake(enc->fps_den, enc->fps_num);
  1073. CMTime off = CMTimeMultiply(dur, 2);
  1074. CMTime pts = CMTimeMake(frame->pts, enc->fps_num);
  1075. CVPixelBufferRef pixbuf = NULL;
  1076. if (!get_cached_pixel_buffer(enc, &pixbuf)) {
  1077. VT_BLOG(LOG_ERROR, "Unable to create pixel buffer");
  1078. goto fail;
  1079. }
  1080. code = CVPixelBufferLockBaseAddress(pixbuf, 0);
  1081. if (code != noErr) {
  1082. goto fail;
  1083. }
  1084. for (int i = 0; i < MAX_AV_PLANES; i++) {
  1085. if (frame->data[i] == NULL)
  1086. break;
  1087. uint8_t *p = (uint8_t *)CVPixelBufferGetBaseAddressOfPlane(
  1088. pixbuf, i);
  1089. uint8_t *f = frame->data[i];
  1090. size_t plane_linesize =
  1091. CVPixelBufferGetBytesPerRowOfPlane(pixbuf, i);
  1092. size_t plane_height = CVPixelBufferGetHeightOfPlane(pixbuf, i);
  1093. for (size_t j = 0; j < plane_height; j++) {
  1094. memcpy(p, f, frame->linesize[i]);
  1095. p += plane_linesize;
  1096. f += frame->linesize[i];
  1097. }
  1098. }
  1099. code = CVPixelBufferUnlockBaseAddress(pixbuf, 0);
  1100. if (code != noErr) {
  1101. goto fail;
  1102. }
  1103. code = VTCompressionSessionEncodeFrame(enc->session, pixbuf, pts, dur,
  1104. NULL, pixbuf, NULL);
  1105. if (code != noErr) {
  1106. goto fail;
  1107. }
  1108. CMSampleBufferRef buffer =
  1109. (CMSampleBufferRef)CMSimpleQueueDequeue(enc->queue);
  1110. // No samples waiting in the queue
  1111. if (buffer == NULL)
  1112. return true;
  1113. *received_packet = true;
  1114. return parse_sample(enc, buffer, packet, off);
  1115. fail:
  1116. return false;
  1117. }
  1118. static bool vt_extra_data(void *data, uint8_t **extra_data, size_t *size)
  1119. {
  1120. struct vt_encoder *enc = (struct vt_encoder *)data;
  1121. *extra_data = enc->extra_data.array;
  1122. *size = enc->extra_data.num;
  1123. return true;
  1124. }
  1125. static const char *vt_getname(void *data)
  1126. {
  1127. struct vt_encoder_type_data *type_data = data;
  1128. if (strcmp("Apple H.264 (HW)", type_data->disp_name) == 0) {
  1129. return obs_module_text("VTH264EncHW");
  1130. } else if (strcmp("Apple H.264 (SW)", type_data->disp_name) == 0) {
  1131. return obs_module_text("VTH264EncSW");
  1132. #ifdef ENABLE_HEVC
  1133. } else if (strcmp("Apple HEVC (HW)", type_data->disp_name) == 0) {
  1134. return obs_module_text("VTHEVCEncHW");
  1135. } else if (strcmp("Apple HEVC (AVE)", type_data->disp_name) == 0) {
  1136. return obs_module_text("VTHEVCEncT2");
  1137. } else if (strcmp("Apple HEVC (SW)", type_data->disp_name) == 0) {
  1138. return obs_module_text("VTHEVCEncSW");
  1139. #endif
  1140. } else if (strncmp("AppleProResHW", type_data->disp_name, 13) == 0) {
  1141. return obs_module_text("VTProResEncHW");
  1142. } else if (strncmp("Apple ProRes", type_data->disp_name, 12) == 0) {
  1143. return obs_module_text("VTProResEncSW");
  1144. }
  1145. return type_data->disp_name;
  1146. }
  1147. static bool rate_control_limit_bitrate_modified(obs_properties_t *ppts,
  1148. obs_property_t *p,
  1149. obs_data_t *settings)
  1150. {
  1151. bool has_bitrate = true;
  1152. bool can_limit_bitrate = true;
  1153. bool use_limit_bitrate = obs_data_get_bool(settings, "limit_bitrate");
  1154. const char *rate_control =
  1155. obs_data_get_string(settings, "rate_control");
  1156. if (strcmp(rate_control, "CBR") == 0) {
  1157. can_limit_bitrate = false;
  1158. has_bitrate = true;
  1159. } else if (strcmp(rate_control, "CRF") == 0) {
  1160. can_limit_bitrate = true;
  1161. has_bitrate = false;
  1162. } else if (strcmp(rate_control, "ABR") == 0) {
  1163. can_limit_bitrate = true;
  1164. has_bitrate = true;
  1165. }
  1166. p = obs_properties_get(ppts, "limit_bitrate");
  1167. obs_property_set_visible(p, can_limit_bitrate);
  1168. p = obs_properties_get(ppts, "max_bitrate");
  1169. obs_property_set_visible(p, can_limit_bitrate && use_limit_bitrate);
  1170. p = obs_properties_get(ppts, "max_bitrate_window");
  1171. obs_property_set_visible(p, can_limit_bitrate && use_limit_bitrate);
  1172. p = obs_properties_get(ppts, "bitrate");
  1173. obs_property_set_visible(p, has_bitrate);
  1174. p = obs_properties_get(ppts, "quality");
  1175. obs_property_set_visible(p, !has_bitrate);
  1176. return true;
  1177. }
  1178. static obs_properties_t *vt_properties_h26x(void *data __unused,
  1179. void *type_data)
  1180. {
  1181. struct vt_encoder_type_data *encoder_type_data = type_data;
  1182. obs_properties_t *props = obs_properties_create();
  1183. obs_property_t *p;
  1184. p = obs_properties_add_list(props, "rate_control",
  1185. obs_module_text("RateControl"),
  1186. OBS_COMBO_TYPE_LIST,
  1187. OBS_COMBO_FORMAT_STRING);
  1188. if (__builtin_available(macOS 13.0, *)) {
  1189. if (encoder_type_data->hardware_accelerated &&
  1190. is_apple_silicon) {
  1191. obs_property_list_add_string(p, "CBR", "CBR");
  1192. }
  1193. }
  1194. obs_property_list_add_string(p, "ABR", "ABR");
  1195. if (encoder_type_data->hardware_accelerated && is_apple_silicon) {
  1196. obs_property_list_add_string(p, "CRF", "CRF");
  1197. }
  1198. obs_property_set_modified_callback(p,
  1199. rate_control_limit_bitrate_modified);
  1200. p = obs_properties_add_int(props, "bitrate", obs_module_text("Bitrate"),
  1201. 50, 10000000, 50);
  1202. obs_property_int_set_suffix(p, " Kbps");
  1203. obs_properties_add_int_slider(props, "quality",
  1204. obs_module_text("Quality"), 0, 100, 1);
  1205. p = obs_properties_add_bool(props, "limit_bitrate",
  1206. obs_module_text("UseMaxBitrate"));
  1207. obs_property_set_modified_callback(p,
  1208. rate_control_limit_bitrate_modified);
  1209. p = obs_properties_add_int(props, "max_bitrate",
  1210. obs_module_text("MaxBitrate"), 50, 10000000,
  1211. 50);
  1212. obs_property_int_set_suffix(p, " Kbps");
  1213. p = obs_properties_add_float(props, "max_bitrate_window",
  1214. obs_module_text("MaxBitrateWindow"), 0.10f,
  1215. 10.0f, 0.25f);
  1216. obs_property_float_set_suffix(p, " s");
  1217. p = obs_properties_add_int(props, "keyint_sec",
  1218. obs_module_text("KeyframeIntervalSec"), 0,
  1219. 20, 1);
  1220. obs_property_int_set_suffix(p, " s");
  1221. p = obs_properties_add_list(props, "profile",
  1222. obs_module_text("Profile"),
  1223. OBS_COMBO_TYPE_LIST,
  1224. OBS_COMBO_FORMAT_STRING);
  1225. if (encoder_type_data->codec_type == kCMVideoCodecType_H264) {
  1226. obs_property_list_add_string(p, "baseline", "baseline");
  1227. obs_property_list_add_string(p, "main", "main");
  1228. obs_property_list_add_string(p, "high", "high");
  1229. #ifdef ENABLE_HEVC
  1230. } else if (encoder_type_data->codec_type == kCMVideoCodecType_HEVC) {
  1231. obs_property_list_add_string(p, "main", "main");
  1232. obs_property_list_add_string(p, "main10", "main10");
  1233. if (__builtin_available(macOS 12.3, *)) {
  1234. obs_property_list_add_string(p, "main 4:2:2 10",
  1235. "main42210");
  1236. }
  1237. #endif
  1238. }
  1239. obs_properties_add_bool(props, "bframes",
  1240. obs_module_text("UseBFrames"));
  1241. return props;
  1242. }
  1243. static obs_properties_t *vt_properties_prores(void *data __unused,
  1244. void *type_data)
  1245. {
  1246. struct vt_encoder_type_data *encoder_type_data = type_data;
  1247. obs_properties_t *props = obs_properties_create();
  1248. obs_property_t *p;
  1249. p = obs_properties_add_list(props, "codec_type",
  1250. obs_module_text("ProResCodec"),
  1251. OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT);
  1252. uint32_t codec_availability_flags = 0;
  1253. size_t size = 0;
  1254. struct vt_prores_encoder_data *encoder_list = NULL;
  1255. if (encoder_type_data->hardware_accelerated) {
  1256. size = vt_prores_hardware_encoder_list.num;
  1257. encoder_list = vt_prores_hardware_encoder_list.array;
  1258. } else {
  1259. size = vt_prores_software_encoder_list.num;
  1260. encoder_list = vt_prores_software_encoder_list.array;
  1261. }
  1262. for (size_t i = 0; i < size; ++i) {
  1263. switch (encoder_list[i].codec_type) {
  1264. case kCMVideoCodecType_AppleProRes4444XQ:
  1265. codec_availability_flags |= (1 << 0);
  1266. break;
  1267. case kCMVideoCodecType_AppleProRes4444:
  1268. codec_availability_flags |= (1 << 1);
  1269. break;
  1270. case kCMVideoCodecType_AppleProRes422Proxy:
  1271. codec_availability_flags |= (1 << 2);
  1272. break;
  1273. case kCMVideoCodecType_AppleProRes422LT:
  1274. codec_availability_flags |= (1 << 3);
  1275. break;
  1276. case kCMVideoCodecType_AppleProRes422:
  1277. codec_availability_flags |= (1 << 4);
  1278. break;
  1279. case kCMVideoCodecType_AppleProRes422HQ:
  1280. codec_availability_flags |= (1 << 5);
  1281. break;
  1282. }
  1283. }
  1284. if (codec_availability_flags & (1 << 0))
  1285. obs_property_list_add_int(p, obs_module_text("ProRes4444XQ"),
  1286. kCMVideoCodecType_AppleProRes4444XQ);
  1287. if (codec_availability_flags & (1 << 1))
  1288. obs_property_list_add_int(p, obs_module_text("ProRes4444"),
  1289. kCMVideoCodecType_AppleProRes4444);
  1290. if (codec_availability_flags & (1 << 2))
  1291. obs_property_list_add_int(
  1292. p, obs_module_text("ProRes422Proxy"),
  1293. kCMVideoCodecType_AppleProRes422Proxy);
  1294. if (codec_availability_flags & (1 << 3))
  1295. obs_property_list_add_int(p, obs_module_text("ProRes422LT"),
  1296. kCMVideoCodecType_AppleProRes422LT);
  1297. if (codec_availability_flags & (1 << 4))
  1298. obs_property_list_add_int(p, obs_module_text("ProRes422"),
  1299. kCMVideoCodecType_AppleProRes422);
  1300. if (codec_availability_flags & (1 << 5))
  1301. obs_property_list_add_int(p, obs_module_text("ProRes422HQ"),
  1302. kCMVideoCodecType_AppleProRes422HQ);
  1303. return props;
  1304. }
  1305. static void vt_defaults(obs_data_t *settings, void *data)
  1306. {
  1307. struct vt_encoder_type_data *type_data = data;
  1308. obs_data_set_default_string(settings, "rate_control", "ABR");
  1309. if (__builtin_available(macOS 13.0, *)) {
  1310. if (type_data->hardware_accelerated && is_apple_silicon) {
  1311. obs_data_set_default_string(settings, "rate_control",
  1312. "CBR");
  1313. }
  1314. }
  1315. obs_data_set_default_int(settings, "bitrate", 2500);
  1316. obs_data_set_default_int(settings, "quality", 60);
  1317. obs_data_set_default_bool(settings, "limit_bitrate", false);
  1318. obs_data_set_default_int(settings, "max_bitrate", 2500);
  1319. obs_data_set_default_double(settings, "max_bitrate_window", 1.5f);
  1320. obs_data_set_default_int(settings, "keyint_sec", 0);
  1321. obs_data_set_default_string(
  1322. settings, "profile",
  1323. type_data->codec_type == kCMVideoCodecType_H264 ? "high"
  1324. : "main");
  1325. obs_data_set_default_int(settings, "codec_type",
  1326. kCMVideoCodecType_AppleProRes422);
  1327. obs_data_set_default_bool(settings, "bframes", true);
  1328. }
  1329. static void vt_free_type_data(void *data)
  1330. {
  1331. struct vt_encoder_type_data *type_data = data;
  1332. bfree((char *)type_data->disp_name);
  1333. bfree((char *)type_data->id);
  1334. bfree(type_data);
  1335. }
  1336. static inline void
  1337. vt_add_prores_encoder_data_to_list(CFDictionaryRef encoder_dict,
  1338. FourCharCode codec_type)
  1339. {
  1340. struct vt_prores_encoder_data *encoder_data = NULL;
  1341. CFBooleanRef hardware_accelerated = CFDictionaryGetValue(
  1342. encoder_dict, kVTVideoEncoderList_IsHardwareAccelerated);
  1343. if (hardware_accelerated == kCFBooleanTrue)
  1344. encoder_data =
  1345. da_push_back_new(vt_prores_hardware_encoder_list);
  1346. else
  1347. encoder_data =
  1348. da_push_back_new(vt_prores_software_encoder_list);
  1349. encoder_data->encoder_id = CFDictionaryGetValue(
  1350. encoder_dict, kVTVideoEncoderList_EncoderID);
  1351. encoder_data->codec_type = codec_type;
  1352. }
  1353. static CFComparisonResult compare_encoder_list(const void *left_val,
  1354. const void *right_val,
  1355. void *context __unused)
  1356. {
  1357. CFDictionaryRef left = (CFDictionaryRef)left_val;
  1358. CFDictionaryRef right = (CFDictionaryRef)right_val;
  1359. CFNumberRef left_codec_num =
  1360. CFDictionaryGetValue(left, kVTVideoEncoderList_CodecType);
  1361. CFNumberRef right_codec_num =
  1362. CFDictionaryGetValue(right, kVTVideoEncoderList_CodecType);
  1363. CFComparisonResult result =
  1364. CFNumberCompare(left_codec_num, right_codec_num, NULL);
  1365. if (result != kCFCompareEqualTo)
  1366. return result;
  1367. CFBooleanRef left_hardware_accel = CFDictionaryGetValue(
  1368. left, kVTVideoEncoderList_IsHardwareAccelerated);
  1369. CFBooleanRef right_hardware_accel = CFDictionaryGetValue(
  1370. right, kVTVideoEncoderList_IsHardwareAccelerated);
  1371. if (left_hardware_accel == right_hardware_accel)
  1372. return kCFCompareEqualTo;
  1373. else if (left_hardware_accel == kCFBooleanTrue)
  1374. return kCFCompareGreaterThan;
  1375. else
  1376. return kCFCompareLessThan;
  1377. }
  1378. OBS_DECLARE_MODULE()
  1379. OBS_MODULE_USE_DEFAULT_LOCALE("mac-videotoolbox", "en-US")
  1380. dispatch_group_t encoder_list_dispatch_group;
  1381. CFArrayRef encoder_list_const;
  1382. bool obs_module_load(void)
  1383. {
  1384. dispatch_queue_t queue =
  1385. dispatch_queue_create("Encoder list load queue", NULL);
  1386. encoder_list_dispatch_group = dispatch_group_create();
  1387. dispatch_group_async(encoder_list_dispatch_group, queue, ^{
  1388. VTCopyVideoEncoderList(NULL, &encoder_list_const);
  1389. });
  1390. // The group dispatch keeps a reference until it's finished
  1391. dispatch_release(queue);
  1392. #ifndef __aarch64__
  1393. is_apple_silicon = os_get_emulation_status();
  1394. #endif
  1395. return true;
  1396. }
  1397. void obs_module_post_load(void)
  1398. {
  1399. struct obs_encoder_info info = {
  1400. .type = OBS_ENCODER_VIDEO,
  1401. .get_name = vt_getname,
  1402. .create = vt_create,
  1403. .destroy = vt_destroy,
  1404. .encode = vt_encode,
  1405. .update = vt_update,
  1406. .get_defaults2 = vt_defaults,
  1407. .get_extra_data = vt_extra_data,
  1408. .free_type_data = vt_free_type_data,
  1409. .caps = OBS_ENCODER_CAP_DYN_BITRATE,
  1410. };
  1411. da_init(vt_prores_hardware_encoder_list);
  1412. da_init(vt_prores_software_encoder_list);
  1413. dispatch_group_wait(encoder_list_dispatch_group, DISPATCH_TIME_FOREVER);
  1414. dispatch_release(encoder_list_dispatch_group);
  1415. CFIndex size = CFArrayGetCount(encoder_list_const);
  1416. CFMutableArrayRef encoder_list = CFArrayCreateMutableCopy(
  1417. kCFAllocatorDefault, size, encoder_list_const);
  1418. CFRelease(encoder_list_const);
  1419. CFArraySortValues(encoder_list, CFRangeMake(0, size),
  1420. &compare_encoder_list, NULL);
  1421. for (CFIndex i = 0; i < size; i++) {
  1422. CFDictionaryRef encoder_dict =
  1423. CFArrayGetValueAtIndex(encoder_list, i);
  1424. CMVideoCodecType codec_type = 0;
  1425. {
  1426. CFNumberRef codec_type_num = CFDictionaryGetValue(
  1427. encoder_dict, kVTVideoEncoderList_CodecType);
  1428. CFNumberGetValue(codec_type_num, kCFNumberSInt32Type,
  1429. &codec_type);
  1430. }
  1431. switch (codec_type) {
  1432. case kCMVideoCodecType_H264:
  1433. info.get_properties2 = vt_properties_h26x;
  1434. info.codec = "h264";
  1435. break;
  1436. #ifdef ENABLE_HEVC
  1437. case kCMVideoCodecType_HEVC:
  1438. info.get_properties2 = vt_properties_h26x;
  1439. info.codec = "hevc";
  1440. break;
  1441. #endif
  1442. // 422 is used as a marker for all ProRes types,
  1443. // since the type is stored as a profile
  1444. case kCMVideoCodecType_AppleProRes422:
  1445. info.get_properties2 = vt_properties_prores;
  1446. info.codec = "prores";
  1447. vt_add_prores_encoder_data_to_list(encoder_dict,
  1448. codec_type);
  1449. break;
  1450. case kCMVideoCodecType_AppleProRes4444XQ:
  1451. case kCMVideoCodecType_AppleProRes4444:
  1452. case kCMVideoCodecType_AppleProRes422Proxy:
  1453. case kCMVideoCodecType_AppleProRes422LT:
  1454. case kCMVideoCodecType_AppleProRes422HQ:
  1455. vt_add_prores_encoder_data_to_list(encoder_dict,
  1456. codec_type);
  1457. continue;
  1458. default:
  1459. continue;
  1460. }
  1461. CFStringRef EncoderID = CFDictionaryGetValue(
  1462. encoder_dict, kVTVideoEncoderList_EncoderID);
  1463. CFIndex id_len =
  1464. CFStringGetMaximumSizeOfFileSystemRepresentation(
  1465. EncoderID);
  1466. char *id = bzalloc(id_len + 1);
  1467. CFStringGetFileSystemRepresentation(EncoderID, id, id_len);
  1468. CFStringRef DisplayName = CFDictionaryGetValue(
  1469. encoder_dict, kVTVideoEncoderList_DisplayName);
  1470. CFIndex disp_name_len =
  1471. CFStringGetMaximumSizeOfFileSystemRepresentation(
  1472. DisplayName);
  1473. char *disp_name = bzalloc(disp_name_len + 1);
  1474. CFStringGetFileSystemRepresentation(DisplayName, disp_name,
  1475. disp_name_len);
  1476. CFBooleanRef hardware_ref = CFDictionaryGetValue(
  1477. encoder_dict,
  1478. kVTVideoEncoderList_IsHardwareAccelerated);
  1479. bool hardware_accelerated =
  1480. (hardware_ref) ? CFBooleanGetValue(hardware_ref)
  1481. : false;
  1482. info.id = id;
  1483. struct vt_encoder_type_data *type_data =
  1484. bzalloc(sizeof(struct vt_encoder_type_data));
  1485. type_data->disp_name = disp_name;
  1486. type_data->id = id;
  1487. type_data->codec_type = codec_type;
  1488. type_data->hardware_accelerated = hardware_accelerated;
  1489. info.type_data = type_data;
  1490. obs_register_encoder(&info);
  1491. }
  1492. CFRelease(encoder_list);
  1493. VT_LOG(LOG_INFO, "Added VideoToolbox encoders");
  1494. }
  1495. void obs_module_unload(void)
  1496. {
  1497. da_free(vt_prores_hardware_encoder_list);
  1498. da_free(vt_prores_software_encoder_list);
  1499. }