encoder.c 50 KB

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