encoder.c 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748
  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. static bool set_video_format(struct vt_encoder *enc, enum video_format format,
  644. enum video_range_type range)
  645. {
  646. bool full_range = range == VIDEO_RANGE_FULL;
  647. switch (format) {
  648. case VIDEO_FORMAT_I420:
  649. enc->vt_pix_fmt =
  650. full_range
  651. ? kCVPixelFormatType_420YpCbCr8PlanarFullRange
  652. : kCVPixelFormatType_420YpCbCr8Planar;
  653. return true;
  654. case VIDEO_FORMAT_NV12:
  655. enc->vt_pix_fmt =
  656. full_range
  657. ? kCVPixelFormatType_420YpCbCr8BiPlanarFullRange
  658. : kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange;
  659. return true;
  660. case VIDEO_FORMAT_P010:
  661. if (enc->codec_type == kCMVideoCodecType_HEVC) {
  662. enc->vt_pix_fmt =
  663. full_range
  664. ? kCVPixelFormatType_420YpCbCr10BiPlanarFullRange
  665. : kCVPixelFormatType_420YpCbCr10BiPlanarVideoRange;
  666. return true;
  667. }
  668. break;
  669. case VIDEO_FORMAT_P216:
  670. if (!full_range) {
  671. enc->vt_pix_fmt =
  672. kCVPixelFormatType_422YpCbCr16BiPlanarVideoRange;
  673. return true;
  674. }
  675. break;
  676. case VIDEO_FORMAT_P416:
  677. if (!full_range) {
  678. enc->vt_pix_fmt =
  679. kCVPixelFormatType_444YpCbCr16BiPlanarVideoRange;
  680. return true;
  681. }
  682. break;
  683. default:
  684. return false;
  685. }
  686. return false;
  687. }
  688. static bool update_params(struct vt_encoder *enc, obs_data_t *settings)
  689. {
  690. video_t *video = obs_encoder_video(enc->encoder);
  691. const struct video_output_info *voi = video_output_get_info(video);
  692. const char *codec = obs_encoder_get_codec(enc->encoder);
  693. if (strcmp(codec, "h264") == 0) {
  694. enc->codec_type = kCMVideoCodecType_H264;
  695. obs_data_set_int(settings, "codec_type", enc->codec_type);
  696. #ifdef ENABLE_HEVC
  697. } else if (strcmp(codec, "hevc") == 0) {
  698. enc->codec_type = kCMVideoCodecType_HEVC;
  699. obs_data_set_int(settings, "codec_type", enc->codec_type);
  700. #endif
  701. } else {
  702. enc->codec_type = (CMVideoCodecType)obs_data_get_int(
  703. settings, "codec_type");
  704. }
  705. if (!set_video_format(enc, voi->format, voi->range)) {
  706. obs_encoder_set_last_error(
  707. enc->encoder,
  708. obs_module_text("ColorFormatUnsupported"));
  709. VT_BLOG(LOG_WARNING, "Unsupported color format selected");
  710. return false;
  711. }
  712. enc->colorspace = voi->colorspace;
  713. enc->width = obs_encoder_get_width(enc->encoder);
  714. enc->height = obs_encoder_get_height(enc->encoder);
  715. enc->fps_num = voi->fps_num;
  716. enc->fps_den = voi->fps_den;
  717. enc->keyint = (uint32_t)obs_data_get_int(settings, "keyint_sec");
  718. enc->rate_control = obs_data_get_string(settings, "rate_control");
  719. enc->bitrate = (uint32_t)obs_data_get_int(settings, "bitrate");
  720. enc->quality = ((float)obs_data_get_int(settings, "quality")) / 100;
  721. enc->profile = obs_data_get_string(settings, "profile");
  722. enc->limit_bitrate = obs_data_get_bool(settings, "limit_bitrate");
  723. enc->rc_max_bitrate =
  724. (uint32_t)obs_data_get_int(settings, "max_bitrate");
  725. enc->rc_max_bitrate_window =
  726. obs_data_get_double(settings, "max_bitrate_window");
  727. enc->bframes = obs_data_get_bool(settings, "bframes");
  728. return true;
  729. }
  730. static bool vt_update(void *data, obs_data_t *settings)
  731. {
  732. struct vt_encoder *enc = data;
  733. uint32_t old_bitrate = enc->bitrate;
  734. bool old_limit_bitrate = enc->limit_bitrate;
  735. update_params(enc, settings);
  736. if (old_bitrate == enc->bitrate &&
  737. old_limit_bitrate == enc->limit_bitrate)
  738. return true;
  739. OSStatus code = session_set_bitrate(enc->session, enc->rate_control,
  740. enc->bitrate, enc->quality,
  741. enc->limit_bitrate,
  742. enc->rc_max_bitrate,
  743. enc->rc_max_bitrate_window);
  744. if (code != noErr)
  745. VT_BLOG(LOG_WARNING, "Failed to set bitrate to session");
  746. dump_encoder_info(enc);
  747. return true;
  748. }
  749. static void *vt_create(obs_data_t *settings, obs_encoder_t *encoder)
  750. {
  751. struct vt_encoder *enc = bzalloc(sizeof(struct vt_encoder));
  752. OSStatus code;
  753. enc->encoder = encoder;
  754. enc->vt_encoder_id = obs_encoder_get_id(encoder);
  755. if (!update_params(enc, settings))
  756. goto fail;
  757. code = CMSimpleQueueCreate(NULL, 100, &enc->queue);
  758. if (code != noErr) {
  759. goto fail;
  760. }
  761. if (!create_encoder(enc))
  762. goto fail;
  763. dump_encoder_info(enc);
  764. return enc;
  765. fail:
  766. vt_destroy(enc);
  767. return NULL;
  768. }
  769. static const uint8_t annexb_startcode[4] = {0, 0, 0, 1};
  770. static void packet_put(struct darray *packet, const uint8_t *buf, size_t size)
  771. {
  772. darray_push_back_array(sizeof(uint8_t), packet, buf, size);
  773. }
  774. static void packet_put_startcode(struct darray *packet, int size)
  775. {
  776. assert(size == 3 || size == 4);
  777. packet_put(packet, &annexb_startcode[4 - size], size);
  778. }
  779. static bool handle_prores_packet(struct vt_encoder *enc,
  780. CMSampleBufferRef buffer)
  781. {
  782. OSStatus err = 0;
  783. size_t block_size = 0;
  784. uint8_t *block_buf = NULL;
  785. CMBlockBufferRef block = CMSampleBufferGetDataBuffer(buffer);
  786. if (block == NULL) {
  787. VT_BLOG(LOG_ERROR,
  788. "Failed to get block buffer for ProRes frame.");
  789. return false;
  790. }
  791. err = CMBlockBufferGetDataPointer(block, 0, NULL, &block_size,
  792. (char **)&block_buf);
  793. if (err != 0) {
  794. VT_BLOG(LOG_ERROR,
  795. "Failed to get data buffer pointer for ProRes frame.");
  796. return false;
  797. }
  798. packet_put(&enc->packet_data.da, block_buf, block_size);
  799. return true;
  800. }
  801. static void convert_block_nals_to_annexb(struct vt_encoder *enc,
  802. struct darray *packet,
  803. CMBlockBufferRef block,
  804. int nal_length_bytes)
  805. {
  806. size_t block_size;
  807. uint8_t *block_buf;
  808. CMBlockBufferGetDataPointer(block, 0, NULL, &block_size,
  809. (char **)&block_buf);
  810. size_t bytes_remaining = block_size;
  811. while (bytes_remaining > 0) {
  812. uint32_t nal_size;
  813. if (nal_length_bytes == 1)
  814. nal_size = block_buf[0];
  815. else if (nal_length_bytes == 2)
  816. nal_size = CFSwapInt16BigToHost(
  817. ((uint16_t *)block_buf)[0]);
  818. else if (nal_length_bytes == 4)
  819. nal_size = CFSwapInt32BigToHost(
  820. ((uint32_t *)block_buf)[0]);
  821. else
  822. return;
  823. bytes_remaining -= nal_length_bytes;
  824. block_buf += nal_length_bytes;
  825. if (bytes_remaining < nal_size) {
  826. VT_BLOG(LOG_ERROR, "invalid nal block");
  827. return;
  828. }
  829. packet_put_startcode(packet, 3);
  830. packet_put(packet, block_buf, nal_size);
  831. bytes_remaining -= nal_size;
  832. block_buf += nal_size;
  833. }
  834. }
  835. static bool handle_keyframe(struct vt_encoder *enc,
  836. CMFormatDescriptionRef format_desc,
  837. size_t param_count, struct darray *packet,
  838. struct darray *extra_data)
  839. {
  840. OSStatus code;
  841. const uint8_t *param;
  842. size_t param_size;
  843. for (size_t i = 0; i < param_count; i++) {
  844. if (enc->codec_type == kCMVideoCodecType_H264) {
  845. code = CMVideoFormatDescriptionGetH264ParameterSetAtIndex(
  846. format_desc, i, &param, &param_size, NULL,
  847. NULL);
  848. #ifdef ENABLE_HEVC
  849. } else if (enc->codec_type == kCMVideoCodecType_HEVC) {
  850. code = CMVideoFormatDescriptionGetHEVCParameterSetAtIndex(
  851. format_desc, i, &param, &param_size, NULL,
  852. NULL);
  853. #endif
  854. }
  855. if (code != noErr) {
  856. log_osstatus(LOG_ERROR, enc,
  857. "getting NAL parameter "
  858. "at index",
  859. code);
  860. return false;
  861. }
  862. packet_put_startcode(packet, 4);
  863. packet_put(packet, param, param_size);
  864. }
  865. // if we were passed an extra_data array, fill it with
  866. // SPS, PPS, etc.
  867. if (extra_data != NULL)
  868. packet_put(extra_data, packet->array, packet->num);
  869. return true;
  870. }
  871. static bool convert_sample_to_annexb(struct vt_encoder *enc,
  872. struct darray *packet,
  873. struct darray *extra_data,
  874. CMSampleBufferRef buffer, bool keyframe)
  875. {
  876. OSStatus code;
  877. CMFormatDescriptionRef format_desc =
  878. CMSampleBufferGetFormatDescription(buffer);
  879. size_t param_count;
  880. int nal_length_bytes;
  881. if (enc->codec_type == kCMVideoCodecType_H264) {
  882. code = CMVideoFormatDescriptionGetH264ParameterSetAtIndex(
  883. format_desc, 0, NULL, NULL, &param_count,
  884. &nal_length_bytes);
  885. #ifdef ENABLE_HEVC
  886. } else if (enc->codec_type == kCMVideoCodecType_HEVC) {
  887. code = CMVideoFormatDescriptionGetHEVCParameterSetAtIndex(
  888. format_desc, 0, NULL, NULL, &param_count,
  889. &nal_length_bytes);
  890. #endif
  891. }
  892. // it is not clear what errors this function can return
  893. // so we check the two most reasonable
  894. if (code == kCMFormatDescriptionBridgeError_InvalidParameter ||
  895. code == kCMFormatDescriptionError_InvalidParameter) {
  896. VT_BLOG(LOG_WARNING, "assuming 2 parameter sets "
  897. "and 4 byte NAL length header");
  898. param_count = 2;
  899. nal_length_bytes = 4;
  900. } else if (code != noErr) {
  901. log_osstatus(LOG_ERROR, enc,
  902. "getting parameter count from sample", code);
  903. return false;
  904. }
  905. if (keyframe &&
  906. !handle_keyframe(enc, format_desc, param_count, packet, extra_data))
  907. return false;
  908. CMBlockBufferRef block = CMSampleBufferGetDataBuffer(buffer);
  909. convert_block_nals_to_annexb(enc, packet, block, nal_length_bytes);
  910. return true;
  911. }
  912. static bool is_sample_keyframe(CMSampleBufferRef buffer)
  913. {
  914. CFArrayRef attachments =
  915. CMSampleBufferGetSampleAttachmentsArray(buffer, false);
  916. if (attachments != NULL) {
  917. CFDictionaryRef attachment;
  918. CFBooleanRef has_dependencies;
  919. attachment =
  920. (CFDictionaryRef)CFArrayGetValueAtIndex(attachments, 0);
  921. has_dependencies = (CFBooleanRef)CFDictionaryGetValue(
  922. attachment, kCMSampleAttachmentKey_DependsOnOthers);
  923. return has_dependencies == kCFBooleanFalse;
  924. }
  925. return false;
  926. }
  927. static bool parse_sample(struct vt_encoder *enc, CMSampleBufferRef buffer,
  928. struct encoder_packet *packet, CMTime off)
  929. {
  930. CMTime pts = CMSampleBufferGetPresentationTimeStamp(buffer);
  931. CMTime dts = CMSampleBufferGetDecodeTimeStamp(buffer);
  932. if (CMTIME_IS_INVALID(dts))
  933. dts = pts;
  934. // imitate x264's negative dts when bframes might have pts < dts
  935. else if (enc->bframes)
  936. dts = CMTimeSubtract(dts, off);
  937. pts = CMTimeMultiply(pts, enc->fps_num);
  938. dts = CMTimeMultiply(dts, enc->fps_num);
  939. const bool is_avc = enc->codec_type == kCMVideoCodecType_H264;
  940. const bool has_annexb = is_avc ||
  941. (enc->codec_type == kCMVideoCodecType_HEVC);
  942. // All ProRes frames are "keyframes"
  943. const bool keyframe = !has_annexb || is_sample_keyframe(buffer);
  944. da_resize(enc->packet_data, 0);
  945. // If we are still looking for extra data
  946. struct darray *extra_data = NULL;
  947. if (enc->extra_data.num == 0)
  948. extra_data = &enc->extra_data.da;
  949. if (has_annexb) {
  950. if (!convert_sample_to_annexb(enc, &enc->packet_data.da,
  951. extra_data, buffer, keyframe))
  952. goto fail;
  953. } else {
  954. if (!handle_prores_packet(enc, buffer))
  955. goto fail;
  956. }
  957. packet->type = OBS_ENCODER_VIDEO;
  958. packet->pts = (int64_t)(CMTimeGetSeconds(pts));
  959. packet->dts = (int64_t)(CMTimeGetSeconds(dts));
  960. packet->data = enc->packet_data.array;
  961. packet->size = enc->packet_data.num;
  962. packet->keyframe = keyframe;
  963. if (is_avc) {
  964. // VideoToolbox produces packets with priority lower than the RTMP code
  965. // expects, which causes it to be unable to recover from frame drops.
  966. // Fix this by manually adjusting the priority.
  967. uint8_t *start = enc->packet_data.array;
  968. uint8_t *end = start + enc->packet_data.num;
  969. start = (uint8_t *)obs_avc_find_startcode(start, end);
  970. while (true) {
  971. while (start < end && !*(start++))
  972. ;
  973. if (start == end)
  974. break;
  975. const int type = start[0] & 0x1F;
  976. if (type == OBS_NAL_SLICE_IDR ||
  977. type == OBS_NAL_SLICE) {
  978. uint8_t prev_type = (start[0] >> 5) & 0x3;
  979. start[0] &= ~(3 << 5);
  980. if (type == OBS_NAL_SLICE_IDR)
  981. start[0] |= OBS_NAL_PRIORITY_HIGHEST
  982. << 5;
  983. else if (type == OBS_NAL_SLICE &&
  984. prev_type !=
  985. OBS_NAL_PRIORITY_DISPOSABLE)
  986. start[0] |= OBS_NAL_PRIORITY_HIGH << 5;
  987. else
  988. start[0] |= prev_type << 5;
  989. }
  990. start = (uint8_t *)obs_avc_find_startcode(start, end);
  991. }
  992. }
  993. CFRelease(buffer);
  994. return true;
  995. fail:
  996. CFRelease(buffer);
  997. return false;
  998. }
  999. bool get_cached_pixel_buffer(struct vt_encoder *enc, CVPixelBufferRef *buf)
  1000. {
  1001. OSStatus code;
  1002. CVPixelBufferPoolRef pool =
  1003. VTCompressionSessionGetPixelBufferPool(enc->session);
  1004. if (!pool)
  1005. return kCVReturnError;
  1006. CVPixelBufferRef pixbuf;
  1007. code = CVPixelBufferPoolCreatePixelBuffer(NULL, pool, &pixbuf);
  1008. if (code != noErr) {
  1009. goto fail;
  1010. }
  1011. // Why aren't these already set on the pixel buffer?
  1012. // I would have expected pixel buffers from the session's
  1013. // pool to have the correct color space stuff set
  1014. const enum video_colorspace cs = enc->colorspace;
  1015. CVBufferSetAttachment(pixbuf, kCVImageBufferYCbCrMatrixKey,
  1016. obs_to_vt_colorspace(cs),
  1017. kCVAttachmentMode_ShouldPropagate);
  1018. CVBufferSetAttachment(pixbuf, kCVImageBufferColorPrimariesKey,
  1019. obs_to_vt_primaries(cs),
  1020. kCVAttachmentMode_ShouldPropagate);
  1021. CVBufferSetAttachment(pixbuf, kCVImageBufferTransferFunctionKey,
  1022. obs_to_vt_transfer(cs),
  1023. kCVAttachmentMode_ShouldPropagate);
  1024. const bool pq = cs == VIDEO_CS_2100_PQ;
  1025. const bool hlg = cs == VIDEO_CS_2100_HLG;
  1026. if (pq || hlg) {
  1027. const uint16_t hdr_nominal_peak_level =
  1028. pq ? (uint16_t)obs_get_video_hdr_nominal_peak_level()
  1029. : (hlg ? 1000 : 0);
  1030. CFDataRef masteringDisplayColorVolume =
  1031. obs_to_vt_masteringdisplay(hdr_nominal_peak_level);
  1032. CFDataRef contentLightLevel =
  1033. obs_to_vt_contentlightlevelinfo(hdr_nominal_peak_level);
  1034. CVBufferSetAttachment(
  1035. pixbuf, kCVImageBufferMasteringDisplayColorVolumeKey,
  1036. masteringDisplayColorVolume,
  1037. kCVAttachmentMode_ShouldPropagate);
  1038. CVBufferSetAttachment(pixbuf,
  1039. kCVImageBufferContentLightLevelInfoKey,
  1040. contentLightLevel,
  1041. kCVAttachmentMode_ShouldPropagate);
  1042. CFRelease(masteringDisplayColorVolume);
  1043. CFRelease(contentLightLevel);
  1044. }
  1045. *buf = pixbuf;
  1046. return true;
  1047. fail:
  1048. return false;
  1049. }
  1050. static bool vt_encode(void *data, struct encoder_frame *frame,
  1051. struct encoder_packet *packet, bool *received_packet)
  1052. {
  1053. struct vt_encoder *enc = data;
  1054. OSStatus code;
  1055. CMTime dur = CMTimeMake(enc->fps_den, enc->fps_num);
  1056. CMTime off = CMTimeMultiply(dur, 2);
  1057. CMTime pts = CMTimeMake(frame->pts, enc->fps_num);
  1058. CVPixelBufferRef pixbuf = NULL;
  1059. if (!get_cached_pixel_buffer(enc, &pixbuf)) {
  1060. VT_BLOG(LOG_ERROR, "Unable to create pixel buffer");
  1061. goto fail;
  1062. }
  1063. code = CVPixelBufferLockBaseAddress(pixbuf, 0);
  1064. if (code != noErr) {
  1065. goto fail;
  1066. }
  1067. for (int i = 0; i < MAX_AV_PLANES; i++) {
  1068. if (frame->data[i] == NULL)
  1069. break;
  1070. uint8_t *p = (uint8_t *)CVPixelBufferGetBaseAddressOfPlane(
  1071. pixbuf, i);
  1072. uint8_t *f = frame->data[i];
  1073. size_t plane_linesize =
  1074. CVPixelBufferGetBytesPerRowOfPlane(pixbuf, i);
  1075. size_t plane_height = CVPixelBufferGetHeightOfPlane(pixbuf, i);
  1076. for (size_t j = 0; j < plane_height; j++) {
  1077. memcpy(p, f, frame->linesize[i]);
  1078. p += plane_linesize;
  1079. f += frame->linesize[i];
  1080. }
  1081. }
  1082. code = CVPixelBufferUnlockBaseAddress(pixbuf, 0);
  1083. if (code != noErr) {
  1084. goto fail;
  1085. }
  1086. code = VTCompressionSessionEncodeFrame(enc->session, pixbuf, pts, dur,
  1087. NULL, pixbuf, NULL);
  1088. if (code != noErr) {
  1089. goto fail;
  1090. }
  1091. CMSampleBufferRef buffer =
  1092. (CMSampleBufferRef)CMSimpleQueueDequeue(enc->queue);
  1093. // No samples waiting in the queue
  1094. if (buffer == NULL)
  1095. return true;
  1096. *received_packet = true;
  1097. return parse_sample(enc, buffer, packet, off);
  1098. fail:
  1099. return false;
  1100. }
  1101. static bool vt_extra_data(void *data, uint8_t **extra_data, size_t *size)
  1102. {
  1103. struct vt_encoder *enc = (struct vt_encoder *)data;
  1104. *extra_data = enc->extra_data.array;
  1105. *size = enc->extra_data.num;
  1106. return true;
  1107. }
  1108. static const char *vt_getname(void *data)
  1109. {
  1110. struct vt_encoder_type_data *type_data = data;
  1111. if (strcmp("Apple H.264 (HW)", type_data->disp_name) == 0) {
  1112. return obs_module_text("VTH264EncHW");
  1113. } else if (strcmp("Apple H.264 (SW)", type_data->disp_name) == 0) {
  1114. return obs_module_text("VTH264EncSW");
  1115. #ifdef ENABLE_HEVC
  1116. } else if (strcmp("Apple HEVC (HW)", type_data->disp_name) == 0) {
  1117. return obs_module_text("VTHEVCEncHW");
  1118. } else if (strcmp("Apple HEVC (AVE)", type_data->disp_name) == 0) {
  1119. return obs_module_text("VTHEVCEncT2");
  1120. } else if (strcmp("Apple HEVC (SW)", type_data->disp_name) == 0) {
  1121. return obs_module_text("VTHEVCEncSW");
  1122. #endif
  1123. } else if (strncmp("AppleProResHW", type_data->disp_name, 13) == 0) {
  1124. return obs_module_text("VTProResEncHW");
  1125. } else if (strncmp("Apple ProRes", type_data->disp_name, 12) == 0) {
  1126. return obs_module_text("VTProResEncSW");
  1127. }
  1128. return type_data->disp_name;
  1129. }
  1130. static bool rate_control_limit_bitrate_modified(obs_properties_t *ppts,
  1131. obs_property_t *p,
  1132. obs_data_t *settings)
  1133. {
  1134. bool has_bitrate = true;
  1135. bool can_limit_bitrate = true;
  1136. bool use_limit_bitrate = obs_data_get_bool(settings, "limit_bitrate");
  1137. const char *rate_control =
  1138. obs_data_get_string(settings, "rate_control");
  1139. if (strcmp(rate_control, "CBR") == 0) {
  1140. can_limit_bitrate = false;
  1141. has_bitrate = true;
  1142. } else if (strcmp(rate_control, "CRF") == 0) {
  1143. can_limit_bitrate = true;
  1144. has_bitrate = false;
  1145. } else if (strcmp(rate_control, "ABR") == 0) {
  1146. can_limit_bitrate = true;
  1147. has_bitrate = true;
  1148. }
  1149. p = obs_properties_get(ppts, "limit_bitrate");
  1150. obs_property_set_visible(p, can_limit_bitrate);
  1151. p = obs_properties_get(ppts, "max_bitrate");
  1152. obs_property_set_visible(p, can_limit_bitrate && use_limit_bitrate);
  1153. p = obs_properties_get(ppts, "max_bitrate_window");
  1154. obs_property_set_visible(p, can_limit_bitrate && use_limit_bitrate);
  1155. p = obs_properties_get(ppts, "bitrate");
  1156. obs_property_set_visible(p, has_bitrate);
  1157. p = obs_properties_get(ppts, "quality");
  1158. obs_property_set_visible(p, !has_bitrate);
  1159. return true;
  1160. }
  1161. static obs_properties_t *vt_properties_h26x(void *data __unused,
  1162. void *type_data)
  1163. {
  1164. struct vt_encoder_type_data *encoder_type_data = type_data;
  1165. obs_properties_t *props = obs_properties_create();
  1166. obs_property_t *p;
  1167. p = obs_properties_add_list(props, "rate_control",
  1168. obs_module_text("RateControl"),
  1169. OBS_COMBO_TYPE_LIST,
  1170. OBS_COMBO_FORMAT_STRING);
  1171. if (__builtin_available(macOS 13.0, *)) {
  1172. if (encoder_type_data->hardware_accelerated &&
  1173. is_apple_silicon) {
  1174. obs_property_list_add_string(p, "CBR", "CBR");
  1175. }
  1176. }
  1177. obs_property_list_add_string(p, "ABR", "ABR");
  1178. if (encoder_type_data->hardware_accelerated && is_apple_silicon) {
  1179. obs_property_list_add_string(p, "CRF", "CRF");
  1180. }
  1181. obs_property_set_modified_callback(p,
  1182. rate_control_limit_bitrate_modified);
  1183. p = obs_properties_add_int(props, "bitrate", obs_module_text("Bitrate"),
  1184. 50, 10000000, 50);
  1185. obs_property_int_set_suffix(p, " Kbps");
  1186. obs_properties_add_int_slider(props, "quality",
  1187. obs_module_text("Quality"), 0, 100, 1);
  1188. p = obs_properties_add_bool(props, "limit_bitrate",
  1189. obs_module_text("UseMaxBitrate"));
  1190. obs_property_set_modified_callback(p,
  1191. rate_control_limit_bitrate_modified);
  1192. p = obs_properties_add_int(props, "max_bitrate",
  1193. obs_module_text("MaxBitrate"), 50, 10000000,
  1194. 50);
  1195. obs_property_int_set_suffix(p, " Kbps");
  1196. p = obs_properties_add_float(props, "max_bitrate_window",
  1197. obs_module_text("MaxBitrateWindow"), 0.10f,
  1198. 10.0f, 0.25f);
  1199. obs_property_float_set_suffix(p, " s");
  1200. p = obs_properties_add_int(props, "keyint_sec",
  1201. obs_module_text("KeyframeIntervalSec"), 0,
  1202. 20, 1);
  1203. obs_property_int_set_suffix(p, " s");
  1204. p = obs_properties_add_list(props, "profile",
  1205. obs_module_text("Profile"),
  1206. OBS_COMBO_TYPE_LIST,
  1207. OBS_COMBO_FORMAT_STRING);
  1208. if (encoder_type_data->codec_type == kCMVideoCodecType_H264) {
  1209. obs_property_list_add_string(p, "baseline", "baseline");
  1210. obs_property_list_add_string(p, "main", "main");
  1211. obs_property_list_add_string(p, "high", "high");
  1212. #ifdef ENABLE_HEVC
  1213. } else if (encoder_type_data->codec_type == kCMVideoCodecType_HEVC) {
  1214. obs_property_list_add_string(p, "main", "main");
  1215. obs_property_list_add_string(p, "main10", "main10");
  1216. if (__builtin_available(macOS 12.3, *)) {
  1217. obs_property_list_add_string(p, "main 4:2:2 10",
  1218. "main42210");
  1219. }
  1220. #endif
  1221. }
  1222. obs_properties_add_bool(props, "bframes",
  1223. obs_module_text("UseBFrames"));
  1224. return props;
  1225. }
  1226. static obs_properties_t *vt_properties_prores(void *data __unused,
  1227. void *type_data)
  1228. {
  1229. struct vt_encoder_type_data *encoder_type_data = type_data;
  1230. obs_properties_t *props = obs_properties_create();
  1231. obs_property_t *p;
  1232. p = obs_properties_add_list(props, "codec_type",
  1233. obs_module_text("ProResCodec"),
  1234. OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT);
  1235. uint32_t codec_availability_flags = 0;
  1236. size_t size = 0;
  1237. struct vt_prores_encoder_data *encoder_list = NULL;
  1238. if (encoder_type_data->hardware_accelerated) {
  1239. size = vt_prores_hardware_encoder_list.num;
  1240. encoder_list = vt_prores_hardware_encoder_list.array;
  1241. } else {
  1242. size = vt_prores_software_encoder_list.num;
  1243. encoder_list = vt_prores_software_encoder_list.array;
  1244. }
  1245. for (size_t i = 0; i < size; ++i) {
  1246. switch (encoder_list[i].codec_type) {
  1247. case kCMVideoCodecType_AppleProRes4444XQ:
  1248. codec_availability_flags |= (1 << 0);
  1249. break;
  1250. case kCMVideoCodecType_AppleProRes4444:
  1251. codec_availability_flags |= (1 << 1);
  1252. break;
  1253. case kCMVideoCodecType_AppleProRes422Proxy:
  1254. codec_availability_flags |= (1 << 2);
  1255. break;
  1256. case kCMVideoCodecType_AppleProRes422LT:
  1257. codec_availability_flags |= (1 << 3);
  1258. break;
  1259. case kCMVideoCodecType_AppleProRes422:
  1260. codec_availability_flags |= (1 << 4);
  1261. break;
  1262. case kCMVideoCodecType_AppleProRes422HQ:
  1263. codec_availability_flags |= (1 << 5);
  1264. break;
  1265. }
  1266. }
  1267. if (codec_availability_flags & (1 << 0))
  1268. obs_property_list_add_int(p, obs_module_text("ProRes4444XQ"),
  1269. kCMVideoCodecType_AppleProRes4444XQ);
  1270. if (codec_availability_flags & (1 << 1))
  1271. obs_property_list_add_int(p, obs_module_text("ProRes4444"),
  1272. kCMVideoCodecType_AppleProRes4444);
  1273. if (codec_availability_flags & (1 << 2))
  1274. obs_property_list_add_int(
  1275. p, obs_module_text("ProRes422Proxy"),
  1276. kCMVideoCodecType_AppleProRes422Proxy);
  1277. if (codec_availability_flags & (1 << 3))
  1278. obs_property_list_add_int(p, obs_module_text("ProRes422LT"),
  1279. kCMVideoCodecType_AppleProRes422LT);
  1280. if (codec_availability_flags & (1 << 4))
  1281. obs_property_list_add_int(p, obs_module_text("ProRes422"),
  1282. kCMVideoCodecType_AppleProRes422);
  1283. if (codec_availability_flags & (1 << 5))
  1284. obs_property_list_add_int(p, obs_module_text("ProRes422HQ"),
  1285. kCMVideoCodecType_AppleProRes422HQ);
  1286. return props;
  1287. }
  1288. static void vt_defaults(obs_data_t *settings, void *data)
  1289. {
  1290. struct vt_encoder_type_data *type_data = data;
  1291. obs_data_set_default_string(settings, "rate_control", "ABR");
  1292. if (__builtin_available(macOS 13.0, *)) {
  1293. if (type_data->hardware_accelerated && is_apple_silicon) {
  1294. obs_data_set_default_string(settings, "rate_control",
  1295. "CBR");
  1296. }
  1297. }
  1298. obs_data_set_default_int(settings, "bitrate", 2500);
  1299. obs_data_set_default_int(settings, "quality", 60);
  1300. obs_data_set_default_bool(settings, "limit_bitrate", false);
  1301. obs_data_set_default_int(settings, "max_bitrate", 2500);
  1302. obs_data_set_default_double(settings, "max_bitrate_window", 1.5f);
  1303. obs_data_set_default_int(settings, "keyint_sec", 0);
  1304. obs_data_set_default_string(
  1305. settings, "profile",
  1306. type_data->codec_type == kCMVideoCodecType_H264 ? "high"
  1307. : "main");
  1308. obs_data_set_default_int(settings, "codec_type",
  1309. kCMVideoCodecType_AppleProRes422);
  1310. obs_data_set_default_bool(settings, "bframes", true);
  1311. }
  1312. static void vt_free_type_data(void *data)
  1313. {
  1314. struct vt_encoder_type_data *type_data = data;
  1315. bfree((char *)type_data->disp_name);
  1316. bfree((char *)type_data->id);
  1317. bfree(type_data);
  1318. }
  1319. static inline void
  1320. vt_add_prores_encoder_data_to_list(CFDictionaryRef encoder_dict,
  1321. FourCharCode codec_type)
  1322. {
  1323. struct vt_prores_encoder_data *encoder_data = NULL;
  1324. CFBooleanRef hardware_accelerated = CFDictionaryGetValue(
  1325. encoder_dict, kVTVideoEncoderList_IsHardwareAccelerated);
  1326. if (hardware_accelerated == kCFBooleanTrue)
  1327. encoder_data =
  1328. da_push_back_new(vt_prores_hardware_encoder_list);
  1329. else
  1330. encoder_data =
  1331. da_push_back_new(vt_prores_software_encoder_list);
  1332. encoder_data->encoder_id = CFDictionaryGetValue(
  1333. encoder_dict, kVTVideoEncoderList_EncoderID);
  1334. encoder_data->codec_type = codec_type;
  1335. }
  1336. static CFComparisonResult compare_encoder_list(const void *left_val,
  1337. const void *right_val,
  1338. void *context __unused)
  1339. {
  1340. CFDictionaryRef left = (CFDictionaryRef)left_val;
  1341. CFDictionaryRef right = (CFDictionaryRef)right_val;
  1342. CFNumberRef left_codec_num =
  1343. CFDictionaryGetValue(left, kVTVideoEncoderList_CodecType);
  1344. CFNumberRef right_codec_num =
  1345. CFDictionaryGetValue(right, kVTVideoEncoderList_CodecType);
  1346. CFComparisonResult result =
  1347. CFNumberCompare(left_codec_num, right_codec_num, NULL);
  1348. if (result != kCFCompareEqualTo)
  1349. return result;
  1350. CFBooleanRef left_hardware_accel = CFDictionaryGetValue(
  1351. left, kVTVideoEncoderList_IsHardwareAccelerated);
  1352. CFBooleanRef right_hardware_accel = CFDictionaryGetValue(
  1353. right, kVTVideoEncoderList_IsHardwareAccelerated);
  1354. if (left_hardware_accel == right_hardware_accel)
  1355. return kCFCompareEqualTo;
  1356. else if (left_hardware_accel == kCFBooleanTrue)
  1357. return kCFCompareGreaterThan;
  1358. else
  1359. return kCFCompareLessThan;
  1360. }
  1361. OBS_DECLARE_MODULE()
  1362. OBS_MODULE_USE_DEFAULT_LOCALE("mac-videotoolbox", "en-US")
  1363. dispatch_group_t encoder_list_dispatch_group;
  1364. CFArrayRef encoder_list_const;
  1365. bool obs_module_load(void)
  1366. {
  1367. dispatch_queue_t queue =
  1368. dispatch_queue_create("Encoder list load queue", NULL);
  1369. encoder_list_dispatch_group = dispatch_group_create();
  1370. dispatch_group_async(encoder_list_dispatch_group, queue, ^{
  1371. VTCopyVideoEncoderList(NULL, &encoder_list_const);
  1372. });
  1373. // The group dispatch keeps a reference until it's finished
  1374. dispatch_release(queue);
  1375. #ifndef __aarch64__
  1376. is_apple_silicon = os_get_emulation_status();
  1377. #endif
  1378. return true;
  1379. }
  1380. void obs_module_post_load(void)
  1381. {
  1382. struct obs_encoder_info info = {
  1383. .type = OBS_ENCODER_VIDEO,
  1384. .get_name = vt_getname,
  1385. .create = vt_create,
  1386. .destroy = vt_destroy,
  1387. .encode = vt_encode,
  1388. .update = vt_update,
  1389. .get_defaults2 = vt_defaults,
  1390. .get_extra_data = vt_extra_data,
  1391. .free_type_data = vt_free_type_data,
  1392. .caps = OBS_ENCODER_CAP_DYN_BITRATE,
  1393. };
  1394. da_init(vt_prores_hardware_encoder_list);
  1395. da_init(vt_prores_software_encoder_list);
  1396. dispatch_group_wait(encoder_list_dispatch_group, DISPATCH_TIME_FOREVER);
  1397. dispatch_release(encoder_list_dispatch_group);
  1398. CFIndex size = CFArrayGetCount(encoder_list_const);
  1399. CFMutableArrayRef encoder_list = CFArrayCreateMutableCopy(
  1400. kCFAllocatorDefault, size, encoder_list_const);
  1401. CFRelease(encoder_list_const);
  1402. CFArraySortValues(encoder_list, CFRangeMake(0, size),
  1403. &compare_encoder_list, NULL);
  1404. for (CFIndex i = 0; i < size; i++) {
  1405. CFDictionaryRef encoder_dict =
  1406. CFArrayGetValueAtIndex(encoder_list, i);
  1407. CMVideoCodecType codec_type = 0;
  1408. {
  1409. CFNumberRef codec_type_num = CFDictionaryGetValue(
  1410. encoder_dict, kVTVideoEncoderList_CodecType);
  1411. CFNumberGetValue(codec_type_num, kCFNumberSInt32Type,
  1412. &codec_type);
  1413. }
  1414. switch (codec_type) {
  1415. case kCMVideoCodecType_H264:
  1416. info.get_properties2 = vt_properties_h26x;
  1417. info.codec = "h264";
  1418. break;
  1419. #ifdef ENABLE_HEVC
  1420. case kCMVideoCodecType_HEVC:
  1421. info.get_properties2 = vt_properties_h26x;
  1422. info.codec = "hevc";
  1423. break;
  1424. #endif
  1425. // 422 is used as a marker for all ProRes types,
  1426. // since the type is stored as a profile
  1427. case kCMVideoCodecType_AppleProRes422:
  1428. info.get_properties2 = vt_properties_prores;
  1429. info.codec = "prores";
  1430. vt_add_prores_encoder_data_to_list(encoder_dict,
  1431. codec_type);
  1432. break;
  1433. case kCMVideoCodecType_AppleProRes4444XQ:
  1434. case kCMVideoCodecType_AppleProRes4444:
  1435. case kCMVideoCodecType_AppleProRes422Proxy:
  1436. case kCMVideoCodecType_AppleProRes422LT:
  1437. case kCMVideoCodecType_AppleProRes422HQ:
  1438. vt_add_prores_encoder_data_to_list(encoder_dict,
  1439. codec_type);
  1440. continue;
  1441. default:
  1442. continue;
  1443. }
  1444. CFStringRef EncoderID = CFDictionaryGetValue(
  1445. encoder_dict, kVTVideoEncoderList_EncoderID);
  1446. CFIndex id_len =
  1447. CFStringGetMaximumSizeOfFileSystemRepresentation(
  1448. EncoderID);
  1449. char *id = bzalloc(id_len + 1);
  1450. CFStringGetFileSystemRepresentation(EncoderID, id, id_len);
  1451. CFStringRef DisplayName = CFDictionaryGetValue(
  1452. encoder_dict, kVTVideoEncoderList_DisplayName);
  1453. CFIndex disp_name_len =
  1454. CFStringGetMaximumSizeOfFileSystemRepresentation(
  1455. DisplayName);
  1456. char *disp_name = bzalloc(disp_name_len + 1);
  1457. CFStringGetFileSystemRepresentation(DisplayName, disp_name,
  1458. disp_name_len);
  1459. CFBooleanRef hardware_ref = CFDictionaryGetValue(
  1460. encoder_dict,
  1461. kVTVideoEncoderList_IsHardwareAccelerated);
  1462. bool hardware_accelerated =
  1463. (hardware_ref) ? CFBooleanGetValue(hardware_ref)
  1464. : false;
  1465. info.id = id;
  1466. struct vt_encoder_type_data *type_data =
  1467. bzalloc(sizeof(struct vt_encoder_type_data));
  1468. type_data->disp_name = disp_name;
  1469. type_data->id = id;
  1470. type_data->codec_type = codec_type;
  1471. type_data->hardware_accelerated = hardware_accelerated;
  1472. info.type_data = type_data;
  1473. obs_register_encoder(&info);
  1474. }
  1475. CFRelease(encoder_list);
  1476. VT_LOG(LOG_INFO, "Added VideoToolbox encoders");
  1477. }
  1478. void obs_module_unload(void)
  1479. {
  1480. da_free(vt_prores_hardware_encoder_list);
  1481. da_free(vt_prores_software_encoder_list);
  1482. }