encoder.c 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466
  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. struct vt_encoder {
  33. obs_encoder_t *encoder;
  34. const char *vt_encoder_id;
  35. uint32_t width;
  36. uint32_t height;
  37. uint32_t keyint;
  38. uint32_t fps_num;
  39. uint32_t fps_den;
  40. const char *rate_control;
  41. uint32_t bitrate;
  42. float quality;
  43. bool limit_bitrate;
  44. uint32_t rc_max_bitrate;
  45. float rc_max_bitrate_window;
  46. const char *profile;
  47. CMVideoCodecType codec_type;
  48. bool bframes;
  49. int vt_pix_fmt;
  50. enum video_colorspace colorspace;
  51. VTCompressionSessionRef session;
  52. CMSimpleQueueRef queue;
  53. bool hw_enc;
  54. DARRAY(uint8_t) packet_data;
  55. DARRAY(uint8_t) extra_data;
  56. };
  57. static const char *codec_type_to_print_fmt(CMVideoCodecType codec_type)
  58. {
  59. switch (codec_type) {
  60. case kCMVideoCodecType_H264:
  61. return "h264";
  62. case kCMVideoCodecType_HEVC:
  63. return "hevc";
  64. case kCMVideoCodecType_AppleProRes422Proxy:
  65. return "apco";
  66. case kCMVideoCodecType_AppleProRes422LT:
  67. return "apcs";
  68. case kCMVideoCodecType_AppleProRes422:
  69. return "apcn";
  70. case kCMVideoCodecType_AppleProRes422HQ:
  71. return "apch";
  72. default:
  73. return "";
  74. }
  75. }
  76. static void log_osstatus(int log_level, struct vt_encoder *enc,
  77. const char *context, OSStatus code)
  78. {
  79. char *c_str = NULL;
  80. CFErrorRef err = CFErrorCreate(kCFAllocatorDefault,
  81. kCFErrorDomainOSStatus, code, NULL);
  82. CFStringRef str = CFErrorCopyDescription(err);
  83. c_str = cfstr_copy_cstr(str, kCFStringEncodingUTF8);
  84. if (c_str) {
  85. if (enc)
  86. VT_BLOG(log_level, "Error in %s: %s", context, c_str);
  87. else
  88. VT_LOG(log_level, "Error in %s: %s", context, c_str);
  89. }
  90. bfree(c_str);
  91. CFRelease(str);
  92. CFRelease(err);
  93. }
  94. static CFStringRef obs_to_vt_profile(CMVideoCodecType codec_type,
  95. const char *profile)
  96. {
  97. if (codec_type == kCMVideoCodecType_H264) {
  98. if (strcmp(profile, "baseline") == 0)
  99. return kVTProfileLevel_H264_Baseline_AutoLevel;
  100. else if (strcmp(profile, "main") == 0)
  101. return kVTProfileLevel_H264_Main_AutoLevel;
  102. else if (strcmp(profile, "high") == 0)
  103. return kVTProfileLevel_H264_High_AutoLevel;
  104. else
  105. return kVTProfileLevel_H264_Main_AutoLevel;
  106. #ifdef ENABLE_HEVC
  107. } else if (codec_type == kCMVideoCodecType_HEVC) {
  108. if (strcmp(profile, "main") == 0)
  109. return kVTProfileLevel_HEVC_Main_AutoLevel;
  110. if (strcmp(profile, "main10") == 0)
  111. return kVTProfileLevel_HEVC_Main10_AutoLevel;
  112. #if __MAC_OS_X_VERSION_MAX_ALLOWED >= 120300 // macOS 12.3
  113. if (__builtin_available(macOS 12.3, *)) {
  114. if (strcmp(profile, "main42210") == 0)
  115. return kVTProfileLevel_HEVC_Main42210_AutoLevel;
  116. }
  117. #endif // macOS 12.3
  118. return kVTProfileLevel_HEVC_Main_AutoLevel;
  119. #endif // ENABLE_HEVC
  120. } else {
  121. return kVTProfileLevel_H264_Baseline_AutoLevel;
  122. }
  123. }
  124. static CFStringRef obs_to_vt_colorspace(enum video_colorspace cs)
  125. {
  126. if (cs == VIDEO_CS_709)
  127. return kCVImageBufferYCbCrMatrix_ITU_R_709_2;
  128. else if (cs == VIDEO_CS_601)
  129. return kCVImageBufferYCbCrMatrix_ITU_R_601_4;
  130. return NULL;
  131. }
  132. #define STATUS_CHECK(c) \
  133. code = c; \
  134. if (code) { \
  135. log_osstatus(LOG_ERROR, enc, #c, code); \
  136. goto fail; \
  137. }
  138. #define SESSION_CHECK(x) \
  139. if ((code = (x)) != noErr) \
  140. return code;
  141. static OSStatus session_set_prop_float(VTCompressionSessionRef session,
  142. CFStringRef key, float val)
  143. {
  144. CFNumberRef n = CFNumberCreate(NULL, kCFNumberFloat32Type, &val);
  145. OSStatus code = VTSessionSetProperty(session, key, n);
  146. CFRelease(n);
  147. return code;
  148. }
  149. static OSStatus session_set_prop_int(VTCompressionSessionRef session,
  150. CFStringRef key, int32_t val)
  151. {
  152. CFNumberRef n = CFNumberCreate(NULL, kCFNumberSInt32Type, &val);
  153. OSStatus code = VTSessionSetProperty(session, key, n);
  154. CFRelease(n);
  155. return code;
  156. }
  157. static OSStatus session_set_prop_str(VTCompressionSessionRef session,
  158. CFStringRef key, char *val)
  159. {
  160. CFStringRef s = CFStringCreateWithFileSystemRepresentation(NULL, val);
  161. OSStatus code = VTSessionSetProperty(session, key, s);
  162. CFRelease(s);
  163. return code;
  164. }
  165. static OSStatus session_set_prop(VTCompressionSessionRef session,
  166. CFStringRef key, CFTypeRef val)
  167. {
  168. return VTSessionSetProperty(session, key, val);
  169. }
  170. static OSStatus session_set_bitrate(VTCompressionSessionRef session,
  171. const char *rate_control, int new_bitrate,
  172. float quality, bool limit_bitrate,
  173. int max_bitrate, float max_bitrate_window)
  174. {
  175. OSStatus code;
  176. bool can_limit_bitrate;
  177. CFStringRef compressionPropertyKey;
  178. if (strcmp(rate_control, "CBR") == 0) {
  179. compressionPropertyKey =
  180. kVTCompressionPropertyKey_AverageBitRate;
  181. can_limit_bitrate = true;
  182. if (__builtin_available(macOS 13.0, *)) {
  183. #if __MAC_OS_X_VERSION_MAX_ALLOWED >= 130000
  184. #ifdef __aarch64__
  185. if (true) {
  186. #else
  187. if (os_get_emulation_status() == true) {
  188. #endif
  189. compressionPropertyKey =
  190. kVTCompressionPropertyKey_ConstantBitRate;
  191. can_limit_bitrate = false;
  192. } else {
  193. VT_LOG(LOG_WARNING,
  194. "CBR support for VideoToolbox encoder requires Apple Silicon. "
  195. "Will use ABR instead.");
  196. }
  197. #else
  198. VT_LOG(LOG_WARNING,
  199. "CBR support for VideoToolbox not available in this build of OBS. "
  200. "Will use ABR instead.");
  201. #endif
  202. } else {
  203. VT_LOG(LOG_WARNING,
  204. "CBR support for VideoToolbox encoder requires macOS 13 or newer. "
  205. "Will use ABR instead.");
  206. }
  207. } else if (strcmp(rate_control, "ABR") == 0) {
  208. compressionPropertyKey =
  209. kVTCompressionPropertyKey_AverageBitRate;
  210. can_limit_bitrate = true;
  211. } else if (strcmp(rate_control, "CRF") == 0) {
  212. #ifdef __aarch64__
  213. if (true) {
  214. #else
  215. if (os_get_emulation_status() == true) {
  216. #endif
  217. compressionPropertyKey =
  218. kVTCompressionPropertyKey_Quality;
  219. SESSION_CHECK(session_set_prop_float(
  220. session, compressionPropertyKey, quality));
  221. } else {
  222. VT_LOG(LOG_WARNING,
  223. "CRF support for VideoToolbox encoder requires Apple Silicon. "
  224. "Will use ABR instead.");
  225. compressionPropertyKey =
  226. kVTCompressionPropertyKey_AverageBitRate;
  227. }
  228. can_limit_bitrate = true;
  229. } else {
  230. VT_LOG(LOG_ERROR,
  231. "Selected rate control method is not supported: %s",
  232. rate_control);
  233. return kVTParameterErr;
  234. }
  235. if (compressionPropertyKey != kVTCompressionPropertyKey_Quality) {
  236. SESSION_CHECK(session_set_prop_int(
  237. session, compressionPropertyKey, new_bitrate * 1000));
  238. }
  239. if (limit_bitrate && can_limit_bitrate) {
  240. int32_t cpb_size = max_bitrate * 125 * max_bitrate_window;
  241. CFNumberRef cf_cpb_size =
  242. CFNumberCreate(NULL, kCFNumberIntType, &cpb_size);
  243. CFNumberRef cf_cpb_window_s = CFNumberCreate(
  244. NULL, kCFNumberFloatType, &max_bitrate_window);
  245. CFMutableArrayRef rate_control = CFArrayCreateMutable(
  246. kCFAllocatorDefault, 2, &kCFTypeArrayCallBacks);
  247. CFArrayAppendValue(rate_control, cf_cpb_size);
  248. CFArrayAppendValue(rate_control, cf_cpb_window_s);
  249. code = session_set_prop(
  250. session, kVTCompressionPropertyKey_DataRateLimits,
  251. rate_control);
  252. CFRelease(cf_cpb_size);
  253. CFRelease(cf_cpb_window_s);
  254. CFRelease(rate_control);
  255. if (code == kVTPropertyNotSupportedErr) {
  256. log_osstatus(LOG_WARNING, NULL,
  257. "setting DataRateLimits on session", code);
  258. return noErr;
  259. }
  260. }
  261. return noErr;
  262. }
  263. static OSStatus session_set_colorspace(VTCompressionSessionRef session,
  264. enum video_colorspace cs)
  265. {
  266. CFStringRef matrix = obs_to_vt_colorspace(cs);
  267. OSStatus code;
  268. if (matrix != NULL) {
  269. SESSION_CHECK(session_set_prop(
  270. session, kVTCompressionPropertyKey_ColorPrimaries,
  271. kCVImageBufferColorPrimaries_ITU_R_709_2));
  272. SESSION_CHECK(session_set_prop(
  273. session, kVTCompressionPropertyKey_TransferFunction,
  274. kCVImageBufferTransferFunction_ITU_R_709_2));
  275. SESSION_CHECK(session_set_prop(
  276. session, kVTCompressionPropertyKey_YCbCrMatrix,
  277. matrix));
  278. }
  279. return noErr;
  280. }
  281. #undef SESSION_CHECK
  282. void sample_encoded_callback(void *data, void *source, OSStatus status,
  283. VTEncodeInfoFlags info_flags,
  284. CMSampleBufferRef buffer)
  285. {
  286. UNUSED_PARAMETER(status);
  287. UNUSED_PARAMETER(info_flags);
  288. CMSimpleQueueRef queue = data;
  289. CVPixelBufferRef pixbuf = source;
  290. if (buffer != NULL) {
  291. CFRetain(buffer);
  292. CMSimpleQueueEnqueue(queue, buffer);
  293. }
  294. CFRelease(pixbuf);
  295. }
  296. #define ENCODER_ID kVTVideoEncoderSpecification_EncoderID
  297. static inline CFMutableDictionaryRef
  298. create_encoder_spec(const char *vt_encoder_id)
  299. {
  300. CFMutableDictionaryRef encoder_spec = CFDictionaryCreateMutable(
  301. kCFAllocatorDefault, 3, &kCFTypeDictionaryKeyCallBacks,
  302. &kCFTypeDictionaryValueCallBacks);
  303. CFStringRef id =
  304. CFStringCreateWithFileSystemRepresentation(NULL, vt_encoder_id);
  305. CFDictionaryAddValue(encoder_spec, ENCODER_ID, id);
  306. CFRelease(id);
  307. return encoder_spec;
  308. }
  309. static inline CFMutableDictionaryRef
  310. create_prores_encoder_spec(CMVideoCodecType target_codec_type,
  311. bool hardware_accelerated)
  312. {
  313. CFStringRef encoder_id = NULL;
  314. size_t size = 0;
  315. struct vt_prores_encoder_data *encoder_list = NULL;
  316. if (hardware_accelerated) {
  317. size = vt_prores_hardware_encoder_list.num;
  318. encoder_list = vt_prores_hardware_encoder_list.array;
  319. } else {
  320. size = vt_prores_software_encoder_list.num;
  321. encoder_list = vt_prores_software_encoder_list.array;
  322. }
  323. for (size_t i = 0; i < size; ++i) {
  324. if (target_codec_type == encoder_list[i].codec_type) {
  325. encoder_id = encoder_list[i].encoder_id;
  326. }
  327. }
  328. CFMutableDictionaryRef encoder_spec = CFDictionaryCreateMutable(
  329. kCFAllocatorDefault, 1, &kCFTypeDictionaryKeyCallBacks,
  330. &kCFTypeDictionaryValueCallBacks);
  331. CFDictionaryAddValue(encoder_spec, ENCODER_ID, encoder_id);
  332. return encoder_spec;
  333. }
  334. #undef ENCODER_ID
  335. static inline CFMutableDictionaryRef create_pixbuf_spec(struct vt_encoder *enc)
  336. {
  337. CFMutableDictionaryRef pixbuf_spec = CFDictionaryCreateMutable(
  338. kCFAllocatorDefault, 3, &kCFTypeDictionaryKeyCallBacks,
  339. &kCFTypeDictionaryValueCallBacks);
  340. CFNumberRef n =
  341. CFNumberCreate(NULL, kCFNumberSInt32Type, &enc->vt_pix_fmt);
  342. CFDictionaryAddValue(pixbuf_spec, kCVPixelBufferPixelFormatTypeKey, n);
  343. CFRelease(n);
  344. n = CFNumberCreate(NULL, kCFNumberSInt32Type, &enc->width);
  345. CFDictionaryAddValue(pixbuf_spec, kCVPixelBufferWidthKey, n);
  346. CFRelease(n);
  347. n = CFNumberCreate(NULL, kCFNumberSInt32Type, &enc->height);
  348. CFDictionaryAddValue(pixbuf_spec, kCVPixelBufferHeightKey, n);
  349. CFRelease(n);
  350. return pixbuf_spec;
  351. }
  352. static bool create_encoder(struct vt_encoder *enc)
  353. {
  354. OSStatus code;
  355. VTCompressionSessionRef s;
  356. const char *codec_name = obs_encoder_get_codec(enc->encoder);
  357. CFDictionaryRef encoder_spec;
  358. if (strcmp(codec_name, "prores") == 0) {
  359. struct vt_encoder_type_data *type_data =
  360. (struct vt_encoder_type_data *)
  361. obs_encoder_get_type_data(enc->encoder);
  362. encoder_spec = create_prores_encoder_spec(
  363. enc->codec_type, type_data->hardware_accelerated);
  364. } else {
  365. encoder_spec = create_encoder_spec(enc->vt_encoder_id);
  366. }
  367. CFDictionaryRef pixbuf_spec = create_pixbuf_spec(enc);
  368. STATUS_CHECK(VTCompressionSessionCreate(
  369. kCFAllocatorDefault, enc->width, enc->height, enc->codec_type,
  370. encoder_spec, pixbuf_spec, NULL, &sample_encoded_callback,
  371. enc->queue, &s));
  372. CFRelease(encoder_spec);
  373. CFRelease(pixbuf_spec);
  374. CFBooleanRef b = NULL;
  375. code = VTSessionCopyProperty(
  376. s,
  377. kVTCompressionPropertyKey_UsingHardwareAcceleratedVideoEncoder,
  378. NULL, &b);
  379. if (code == noErr && (enc->hw_enc = CFBooleanGetValue(b)))
  380. VT_BLOG(LOG_INFO, "session created with hardware encoding");
  381. else
  382. enc->hw_enc = false;
  383. if (b != NULL)
  384. CFRelease(b);
  385. if (enc->codec_type == kCMVideoCodecType_H264 ||
  386. enc->codec_type == kCMVideoCodecType_HEVC) {
  387. // This can fail when using GPU hardware encoding
  388. code = session_set_prop_int(
  389. s,
  390. kVTCompressionPropertyKey_MaxKeyFrameIntervalDuration,
  391. enc->keyint);
  392. if (code != noErr)
  393. log_osstatus(
  394. LOG_WARNING, enc,
  395. "setting kVTCompressionPropertyKey_MaxKeyFrameIntervalDuration failed, "
  396. "keyframe interval might be incorrect",
  397. code);
  398. STATUS_CHECK(session_set_prop_int(
  399. s, kVTCompressionPropertyKey_MaxKeyFrameInterval,
  400. enc->keyint * ((float)enc->fps_num / enc->fps_den)));
  401. STATUS_CHECK(session_set_prop_float(
  402. s, kVTCompressionPropertyKey_ExpectedFrameRate,
  403. (float)enc->fps_num / enc->fps_den));
  404. STATUS_CHECK(session_set_prop(
  405. s, kVTCompressionPropertyKey_AllowFrameReordering,
  406. enc->bframes ? kCFBooleanTrue : kCFBooleanFalse));
  407. STATUS_CHECK(session_set_prop(
  408. s, kVTCompressionPropertyKey_ProfileLevel,
  409. obs_to_vt_profile(enc->codec_type, enc->profile)));
  410. STATUS_CHECK(session_set_bitrate(
  411. s, enc->rate_control, enc->bitrate, enc->quality,
  412. enc->limit_bitrate, enc->rc_max_bitrate,
  413. enc->rc_max_bitrate_window));
  414. }
  415. // This can fail depending on hardware configuration
  416. code = session_set_prop(s, kVTCompressionPropertyKey_RealTime,
  417. kCFBooleanFalse);
  418. if (code != noErr)
  419. log_osstatus(
  420. LOG_WARNING, enc,
  421. "setting kVTCompressionPropertyKey_RealTime failed, "
  422. "frame delay might be increased",
  423. code);
  424. STATUS_CHECK(session_set_colorspace(s, enc->colorspace));
  425. STATUS_CHECK(VTCompressionSessionPrepareToEncodeFrames(s));
  426. enc->session = s;
  427. return true;
  428. fail:
  429. if (encoder_spec != NULL)
  430. CFRelease(encoder_spec);
  431. if (pixbuf_spec != NULL)
  432. CFRelease(pixbuf_spec);
  433. return false;
  434. }
  435. static void vt_destroy(void *data)
  436. {
  437. struct vt_encoder *enc = data;
  438. if (enc) {
  439. if (enc->session != NULL) {
  440. VTCompressionSessionInvalidate(enc->session);
  441. CFRelease(enc->session);
  442. }
  443. da_free(enc->packet_data);
  444. da_free(enc->extra_data);
  445. bfree(enc);
  446. }
  447. }
  448. static void dump_encoder_info(struct vt_encoder *enc)
  449. {
  450. VT_BLOG(LOG_INFO,
  451. "settings:\n"
  452. "\tvt_encoder_id %s\n"
  453. "\trate_control: %s\n"
  454. "\tbitrate: %d (kbps)\n"
  455. "\tquality: %f\n"
  456. "\tfps_num: %d\n"
  457. "\tfps_den: %d\n"
  458. "\twidth: %d\n"
  459. "\theight: %d\n"
  460. "\tkeyint: %d (s)\n"
  461. "\tlimit_bitrate: %s\n"
  462. "\trc_max_bitrate: %d (kbps)\n"
  463. "\trc_max_bitrate_window: %f (s)\n"
  464. "\thw_enc: %s\n"
  465. "\tprofile: %s\n"
  466. "\tcodec_type: %.4s\n",
  467. enc->vt_encoder_id, enc->rate_control, enc->bitrate,
  468. enc->quality, enc->fps_num, enc->fps_den, enc->width,
  469. enc->height, enc->keyint, enc->limit_bitrate ? "on" : "off",
  470. enc->rc_max_bitrate, enc->rc_max_bitrate_window,
  471. enc->hw_enc ? "on" : "off",
  472. (enc->profile != NULL && !!strlen(enc->profile)) ? enc->profile
  473. : "default",
  474. codec_type_to_print_fmt(enc->codec_type));
  475. }
  476. static bool set_video_format(struct vt_encoder *enc, enum video_format format,
  477. enum video_range_type range)
  478. {
  479. bool full_range = range == VIDEO_RANGE_FULL;
  480. switch (format) {
  481. case VIDEO_FORMAT_I420:
  482. enc->vt_pix_fmt =
  483. full_range
  484. ? kCVPixelFormatType_420YpCbCr8PlanarFullRange
  485. : kCVPixelFormatType_420YpCbCr8Planar;
  486. return true;
  487. case VIDEO_FORMAT_NV12:
  488. enc->vt_pix_fmt =
  489. full_range
  490. ? kCVPixelFormatType_420YpCbCr8BiPlanarFullRange
  491. : kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange;
  492. return true;
  493. default:
  494. return false;
  495. }
  496. }
  497. static bool update_params(struct vt_encoder *enc, obs_data_t *settings)
  498. {
  499. video_t *video = obs_encoder_video(enc->encoder);
  500. const struct video_output_info *voi = video_output_get_info(video);
  501. if (!set_video_format(enc, voi->format, voi->range)) {
  502. obs_encoder_set_last_error(
  503. enc->encoder,
  504. obs_module_text("ColorFormatUnsupported"));
  505. VT_BLOG(LOG_WARNING, "Unsupported color format selected");
  506. return false;
  507. }
  508. enc->colorspace = voi->colorspace;
  509. enc->width = obs_encoder_get_width(enc->encoder);
  510. enc->height = obs_encoder_get_height(enc->encoder);
  511. enc->fps_num = voi->fps_num;
  512. enc->fps_den = voi->fps_den;
  513. enc->keyint = (uint32_t)obs_data_get_int(settings, "keyint_sec");
  514. enc->rate_control = obs_data_get_string(settings, "rate_control");
  515. enc->bitrate = (uint32_t)obs_data_get_int(settings, "bitrate");
  516. enc->quality = ((float)obs_data_get_int(settings, "quality")) / 100;
  517. enc->profile = obs_data_get_string(settings, "profile");
  518. enc->limit_bitrate = obs_data_get_bool(settings, "limit_bitrate");
  519. enc->rc_max_bitrate = obs_data_get_int(settings, "max_bitrate");
  520. enc->rc_max_bitrate_window =
  521. obs_data_get_double(settings, "max_bitrate_window");
  522. enc->bframes = obs_data_get_bool(settings, "bframes");
  523. const char *codec = obs_encoder_get_codec(enc->encoder);
  524. if (strcmp(codec, "h264") == 0) {
  525. enc->codec_type = kCMVideoCodecType_H264;
  526. obs_data_set_int(settings, "codec_type", enc->codec_type);
  527. #ifdef ENABLE_HEVC
  528. } else if (strcmp(codec, "hevc") == 0) {
  529. enc->codec_type = kCMVideoCodecType_HEVC;
  530. obs_data_set_int(settings, "codec_type", enc->codec_type);
  531. #endif
  532. } else {
  533. enc->codec_type = (CMVideoCodecType)obs_data_get_int(
  534. settings, "codec_type");
  535. }
  536. return true;
  537. }
  538. static bool vt_update(void *data, obs_data_t *settings)
  539. {
  540. struct vt_encoder *enc = data;
  541. uint32_t old_bitrate = enc->bitrate;
  542. bool old_limit_bitrate = enc->limit_bitrate;
  543. update_params(enc, settings);
  544. if (old_bitrate == enc->bitrate &&
  545. old_limit_bitrate == enc->limit_bitrate)
  546. return true;
  547. OSStatus code = session_set_bitrate(enc->session, enc->rate_control,
  548. enc->bitrate, enc->quality,
  549. enc->limit_bitrate,
  550. enc->rc_max_bitrate,
  551. enc->rc_max_bitrate_window);
  552. if (code != noErr)
  553. VT_BLOG(LOG_WARNING, "Failed to set bitrate to session");
  554. dump_encoder_info(enc);
  555. return true;
  556. }
  557. static void *vt_create(obs_data_t *settings, obs_encoder_t *encoder)
  558. {
  559. struct vt_encoder *enc = bzalloc(sizeof(struct vt_encoder));
  560. OSStatus code;
  561. enc->encoder = encoder;
  562. enc->vt_encoder_id = obs_encoder_get_id(encoder);
  563. if (!update_params(enc, settings))
  564. goto fail;
  565. STATUS_CHECK(CMSimpleQueueCreate(NULL, 100, &enc->queue));
  566. if (!create_encoder(enc))
  567. goto fail;
  568. dump_encoder_info(enc);
  569. return enc;
  570. fail:
  571. vt_destroy(enc);
  572. return NULL;
  573. }
  574. static const uint8_t annexb_startcode[4] = {0, 0, 0, 1};
  575. static void packet_put(struct darray *packet, const uint8_t *buf, size_t size)
  576. {
  577. darray_push_back_array(sizeof(uint8_t), packet, buf, size);
  578. }
  579. static void packet_put_startcode(struct darray *packet, int size)
  580. {
  581. assert(size == 3 || size == 4);
  582. packet_put(packet, &annexb_startcode[4 - size], size);
  583. }
  584. static bool handle_prores_packet(struct vt_encoder *enc,
  585. CMSampleBufferRef buffer)
  586. {
  587. OSStatus err = 0;
  588. size_t block_size = 0;
  589. uint8_t *block_buf = NULL;
  590. CMBlockBufferRef block = CMSampleBufferGetDataBuffer(buffer);
  591. if (block == NULL) {
  592. VT_BLOG(LOG_ERROR,
  593. "Failed to get block buffer for ProRes frame.");
  594. return false;
  595. }
  596. err = CMBlockBufferGetDataPointer(block, 0, NULL, &block_size,
  597. (char **)&block_buf);
  598. if (err != 0) {
  599. VT_BLOG(LOG_ERROR,
  600. "Failed to get data buffer pointer for ProRes frame.");
  601. return false;
  602. }
  603. packet_put(&enc->packet_data.da, block_buf, block_size);
  604. return true;
  605. }
  606. static void convert_block_nals_to_annexb(struct vt_encoder *enc,
  607. struct darray *packet,
  608. CMBlockBufferRef block,
  609. int nal_length_bytes)
  610. {
  611. size_t block_size;
  612. uint8_t *block_buf;
  613. CMBlockBufferGetDataPointer(block, 0, NULL, &block_size,
  614. (char **)&block_buf);
  615. size_t bytes_remaining = block_size;
  616. while (bytes_remaining > 0) {
  617. uint32_t nal_size;
  618. if (nal_length_bytes == 1)
  619. nal_size = block_buf[0];
  620. else if (nal_length_bytes == 2)
  621. nal_size = CFSwapInt16BigToHost(
  622. ((uint16_t *)block_buf)[0]);
  623. else if (nal_length_bytes == 4)
  624. nal_size = CFSwapInt32BigToHost(
  625. ((uint32_t *)block_buf)[0]);
  626. else
  627. return;
  628. bytes_remaining -= nal_length_bytes;
  629. block_buf += nal_length_bytes;
  630. if (bytes_remaining < nal_size) {
  631. VT_BLOG(LOG_ERROR, "invalid nal block");
  632. return;
  633. }
  634. packet_put_startcode(packet, 3);
  635. packet_put(packet, block_buf, nal_size);
  636. bytes_remaining -= nal_size;
  637. block_buf += nal_size;
  638. }
  639. }
  640. static bool handle_keyframe(struct vt_encoder *enc,
  641. CMFormatDescriptionRef format_desc,
  642. size_t param_count, struct darray *packet,
  643. struct darray *extra_data)
  644. {
  645. OSStatus code;
  646. const uint8_t *param;
  647. size_t param_size;
  648. for (size_t i = 0; i < param_count; i++) {
  649. if (enc->codec_type == kCMVideoCodecType_H264) {
  650. code = CMVideoFormatDescriptionGetH264ParameterSetAtIndex(
  651. format_desc, i, &param, &param_size, NULL,
  652. NULL);
  653. #ifdef ENABLE_HEVC
  654. } else if (enc->codec_type == kCMVideoCodecType_HEVC) {
  655. code = CMVideoFormatDescriptionGetHEVCParameterSetAtIndex(
  656. format_desc, i, &param, &param_size, NULL,
  657. NULL);
  658. #endif
  659. }
  660. if (code != noErr) {
  661. log_osstatus(LOG_ERROR, enc,
  662. "getting NAL parameter "
  663. "at index",
  664. code);
  665. return false;
  666. }
  667. packet_put_startcode(packet, 4);
  668. packet_put(packet, param, param_size);
  669. }
  670. // if we were passed an extra_data array, fill it with
  671. // SPS, PPS, etc.
  672. if (extra_data != NULL)
  673. packet_put(extra_data, packet->array, packet->num);
  674. return true;
  675. }
  676. static bool convert_sample_to_annexb(struct vt_encoder *enc,
  677. struct darray *packet,
  678. struct darray *extra_data,
  679. CMSampleBufferRef buffer, bool keyframe)
  680. {
  681. OSStatus code;
  682. CMFormatDescriptionRef format_desc =
  683. CMSampleBufferGetFormatDescription(buffer);
  684. size_t param_count;
  685. int nal_length_bytes;
  686. if (enc->codec_type == kCMVideoCodecType_H264) {
  687. code = CMVideoFormatDescriptionGetH264ParameterSetAtIndex(
  688. format_desc, 0, NULL, NULL, &param_count,
  689. &nal_length_bytes);
  690. #ifdef ENABLE_HEVC
  691. } else if (enc->codec_type == kCMVideoCodecType_HEVC) {
  692. code = CMVideoFormatDescriptionGetHEVCParameterSetAtIndex(
  693. format_desc, 0, NULL, NULL, &param_count,
  694. &nal_length_bytes);
  695. #endif
  696. }
  697. // it is not clear what errors this function can return
  698. // so we check the two most reasonable
  699. if (code == kCMFormatDescriptionBridgeError_InvalidParameter ||
  700. code == kCMFormatDescriptionError_InvalidParameter) {
  701. VT_BLOG(LOG_WARNING, "assuming 2 parameter sets "
  702. "and 4 byte NAL length header");
  703. param_count = 2;
  704. nal_length_bytes = 4;
  705. } else if (code != noErr) {
  706. log_osstatus(LOG_ERROR, enc,
  707. "getting parameter count from sample", code);
  708. return false;
  709. }
  710. if (keyframe &&
  711. !handle_keyframe(enc, format_desc, param_count, packet, extra_data))
  712. return false;
  713. CMBlockBufferRef block = CMSampleBufferGetDataBuffer(buffer);
  714. convert_block_nals_to_annexb(enc, packet, block, nal_length_bytes);
  715. return true;
  716. }
  717. static bool is_sample_keyframe(CMSampleBufferRef buffer)
  718. {
  719. CFArrayRef attachments =
  720. CMSampleBufferGetSampleAttachmentsArray(buffer, false);
  721. if (attachments != NULL) {
  722. CFDictionaryRef attachment;
  723. CFBooleanRef has_dependencies;
  724. attachment =
  725. (CFDictionaryRef)CFArrayGetValueAtIndex(attachments, 0);
  726. has_dependencies = (CFBooleanRef)CFDictionaryGetValue(
  727. attachment, kCMSampleAttachmentKey_DependsOnOthers);
  728. return has_dependencies == kCFBooleanFalse;
  729. }
  730. return false;
  731. }
  732. static bool parse_sample(struct vt_encoder *enc, CMSampleBufferRef buffer,
  733. struct encoder_packet *packet, CMTime off)
  734. {
  735. int type;
  736. bool should_edit_nal = false;
  737. if (enc->codec_type == kCMVideoCodecType_H264 ||
  738. enc->codec_type == kCMVideoCodecType_HEVC) {
  739. should_edit_nal = true;
  740. }
  741. CMTime pts = CMSampleBufferGetPresentationTimeStamp(buffer);
  742. CMTime dts = CMSampleBufferGetDecodeTimeStamp(buffer);
  743. if (CMTIME_IS_INVALID(dts))
  744. dts = pts;
  745. // imitate x264's negative dts when bframes might have pts < dts
  746. else if (enc->bframes)
  747. dts = CMTimeSubtract(dts, off);
  748. pts = CMTimeMultiply(pts, enc->fps_num);
  749. dts = CMTimeMultiply(dts, enc->fps_num);
  750. // All ProRes frames are "keyframes"
  751. bool keyframe = true;
  752. if (should_edit_nal) {
  753. keyframe = is_sample_keyframe(buffer);
  754. }
  755. da_resize(enc->packet_data, 0);
  756. // If we are still looking for extra data
  757. struct darray *extra_data = NULL;
  758. if (enc->extra_data.num == 0)
  759. extra_data = &enc->extra_data.da;
  760. if (should_edit_nal) {
  761. if (!convert_sample_to_annexb(enc, &enc->packet_data.da,
  762. extra_data, buffer, keyframe))
  763. goto fail;
  764. } else {
  765. if (!handle_prores_packet(enc, buffer))
  766. goto fail;
  767. }
  768. packet->type = OBS_ENCODER_VIDEO;
  769. packet->pts = (int64_t)(CMTimeGetSeconds(pts));
  770. packet->dts = (int64_t)(CMTimeGetSeconds(dts));
  771. packet->data = enc->packet_data.array;
  772. packet->size = enc->packet_data.num;
  773. packet->keyframe = keyframe;
  774. if (should_edit_nal) {
  775. // VideoToolbox produces packets with priority lower than the RTMP code
  776. // expects, which causes it to be unable to recover from frame drops.
  777. // Fix this by manually adjusting the priority.
  778. uint8_t *start = enc->packet_data.array;
  779. uint8_t *end = start + enc->packet_data.num;
  780. start = (uint8_t *)obs_avc_find_startcode(start, end);
  781. while (true) {
  782. while (start < end && !*(start++))
  783. ;
  784. if (start == end)
  785. break;
  786. type = start[0] & 0x1F;
  787. if (type == OBS_NAL_SLICE_IDR ||
  788. type == OBS_NAL_SLICE) {
  789. uint8_t prev_type = (start[0] >> 5) & 0x3;
  790. start[0] &= ~(3 << 5);
  791. if (type == OBS_NAL_SLICE_IDR)
  792. start[0] |= OBS_NAL_PRIORITY_HIGHEST
  793. << 5;
  794. else if (type == OBS_NAL_SLICE &&
  795. prev_type !=
  796. OBS_NAL_PRIORITY_DISPOSABLE)
  797. start[0] |= OBS_NAL_PRIORITY_HIGH << 5;
  798. else
  799. start[0] |= prev_type << 5;
  800. }
  801. start = (uint8_t *)obs_avc_find_startcode(start, end);
  802. }
  803. }
  804. CFRelease(buffer);
  805. return true;
  806. fail:
  807. CFRelease(buffer);
  808. return false;
  809. }
  810. bool get_cached_pixel_buffer(struct vt_encoder *enc, CVPixelBufferRef *buf)
  811. {
  812. OSStatus code;
  813. CVPixelBufferPoolRef pool =
  814. VTCompressionSessionGetPixelBufferPool(enc->session);
  815. if (!pool)
  816. return kCVReturnError;
  817. CVPixelBufferRef pixbuf;
  818. STATUS_CHECK(CVPixelBufferPoolCreatePixelBuffer(NULL, pool, &pixbuf));
  819. // Why aren't these already set on the pixel buffer?
  820. // I would have expected pixel buffers from the session's
  821. // pool to have the correct color space stuff set
  822. CFStringRef matrix = obs_to_vt_colorspace(enc->colorspace);
  823. CVBufferSetAttachment(pixbuf, kCVImageBufferYCbCrMatrixKey, matrix,
  824. kCVAttachmentMode_ShouldPropagate);
  825. CVBufferSetAttachment(pixbuf, kCVImageBufferColorPrimariesKey,
  826. kCVImageBufferColorPrimaries_ITU_R_709_2,
  827. kCVAttachmentMode_ShouldPropagate);
  828. CVBufferSetAttachment(pixbuf, kCVImageBufferTransferFunctionKey,
  829. kCVImageBufferTransferFunction_ITU_R_709_2,
  830. kCVAttachmentMode_ShouldPropagate);
  831. *buf = pixbuf;
  832. return true;
  833. fail:
  834. return false;
  835. }
  836. static bool vt_encode(void *data, struct encoder_frame *frame,
  837. struct encoder_packet *packet, bool *received_packet)
  838. {
  839. struct vt_encoder *enc = data;
  840. OSStatus code;
  841. CMTime dur = CMTimeMake(enc->fps_den, enc->fps_num);
  842. CMTime off = CMTimeMultiply(dur, 2);
  843. CMTime pts = CMTimeMake(frame->pts, enc->fps_num);
  844. CVPixelBufferRef pixbuf = NULL;
  845. if (!get_cached_pixel_buffer(enc, &pixbuf)) {
  846. VT_BLOG(LOG_ERROR, "Unable to create pixel buffer");
  847. goto fail;
  848. }
  849. STATUS_CHECK(CVPixelBufferLockBaseAddress(pixbuf, 0));
  850. for (int i = 0; i < MAX_AV_PLANES; i++) {
  851. if (frame->data[i] == NULL)
  852. break;
  853. uint8_t *p = (uint8_t *)CVPixelBufferGetBaseAddressOfPlane(
  854. pixbuf, i);
  855. uint8_t *f = frame->data[i];
  856. size_t plane_linesize =
  857. CVPixelBufferGetBytesPerRowOfPlane(pixbuf, i);
  858. size_t plane_height = CVPixelBufferGetHeightOfPlane(pixbuf, i);
  859. for (size_t j = 0; j < plane_height; j++) {
  860. memcpy(p, f, frame->linesize[i]);
  861. p += plane_linesize;
  862. f += frame->linesize[i];
  863. }
  864. }
  865. STATUS_CHECK(CVPixelBufferUnlockBaseAddress(pixbuf, 0));
  866. STATUS_CHECK(VTCompressionSessionEncodeFrame(enc->session, pixbuf, pts,
  867. dur, NULL, pixbuf, NULL));
  868. CMSampleBufferRef buffer =
  869. (CMSampleBufferRef)CMSimpleQueueDequeue(enc->queue);
  870. // No samples waiting in the queue
  871. if (buffer == NULL)
  872. return true;
  873. *received_packet = true;
  874. return parse_sample(enc, buffer, packet, off);
  875. fail:
  876. return false;
  877. }
  878. #undef STATUS_CHECK
  879. #undef CFNUM_INT
  880. static bool vt_extra_data(void *data, uint8_t **extra_data, size_t *size)
  881. {
  882. struct vt_encoder *enc = (struct vt_encoder *)data;
  883. *extra_data = enc->extra_data.array;
  884. *size = enc->extra_data.num;
  885. return true;
  886. }
  887. static const char *vt_getname(void *data)
  888. {
  889. struct vt_encoder_type_data *type_data = data;
  890. if (strcmp("Apple H.264 (HW)", type_data->disp_name) == 0) {
  891. return obs_module_text("VTH264EncHW");
  892. } else if (strcmp("Apple H.264 (SW)", type_data->disp_name) == 0) {
  893. return obs_module_text("VTH264EncSW");
  894. #ifdef ENABLE_HEVC
  895. } else if (strcmp("Apple HEVC (HW)", type_data->disp_name) == 0) {
  896. return obs_module_text("VTHEVCEncHW");
  897. } else if (strcmp("Apple HEVC (AVE)", type_data->disp_name) == 0) {
  898. return obs_module_text("VTHEVCEncT2");
  899. } else if (strcmp("Apple HEVC (SW)", type_data->disp_name) == 0) {
  900. return obs_module_text("VTHEVCEncSW");
  901. #endif
  902. } else if (strncmp("AppleProResHW", type_data->disp_name, 13) == 0) {
  903. return obs_module_text("VTProResEncHW");
  904. } else if (strncmp("Apple ProRes", type_data->disp_name, 12) == 0) {
  905. return obs_module_text("VTProResEncSW");
  906. }
  907. return type_data->disp_name;
  908. }
  909. #define TEXT_BITRATE obs_module_text("Bitrate")
  910. #define TEXT_QUALITY obs_module_text("Quality")
  911. #define TEXT_USE_MAX_BITRATE obs_module_text("UseMaxBitrate")
  912. #define TEXT_MAX_BITRATE obs_module_text("MaxBitrate")
  913. #define TEXT_MAX_BITRATE_WINDOW obs_module_text("MaxBitrateWindow")
  914. #define TEXT_KEYINT_SEC obs_module_text("KeyframeIntervalSec")
  915. #define TEXT_PROFILE obs_module_text("Profile")
  916. #define TEXT_BFRAMES obs_module_text("UseBFrames")
  917. #define TEXT_RATE_CONTROL obs_module_text("RateControl")
  918. #define TEXT_PRORES_CODEC obs_module_text("ProResCodec")
  919. static bool rate_control_limit_bitrate_modified(obs_properties_t *ppts,
  920. obs_property_t *p,
  921. obs_data_t *settings)
  922. {
  923. bool has_bitrate = true;
  924. bool can_limit_bitrate = true;
  925. bool use_limit_bitrate = obs_data_get_bool(settings, "limit_bitrate");
  926. const char *rate_control =
  927. obs_data_get_string(settings, "rate_control");
  928. if (strcmp(rate_control, "CBR") == 0) {
  929. can_limit_bitrate = false;
  930. has_bitrate = true;
  931. } else if (strcmp(rate_control, "CRF") == 0) {
  932. can_limit_bitrate = true;
  933. has_bitrate = false;
  934. } else if (strcmp(rate_control, "ABR") == 0) {
  935. can_limit_bitrate = true;
  936. has_bitrate = true;
  937. }
  938. p = obs_properties_get(ppts, "limit_bitrate");
  939. obs_property_set_visible(p, can_limit_bitrate);
  940. p = obs_properties_get(ppts, "max_bitrate");
  941. obs_property_set_visible(p, can_limit_bitrate && use_limit_bitrate);
  942. p = obs_properties_get(ppts, "max_bitrate_window");
  943. obs_property_set_visible(p, can_limit_bitrate && use_limit_bitrate);
  944. p = obs_properties_get(ppts, "bitrate");
  945. obs_property_set_visible(p, has_bitrate);
  946. p = obs_properties_get(ppts, "quality");
  947. obs_property_set_visible(p, !has_bitrate);
  948. return true;
  949. }
  950. static obs_properties_t *vt_properties_h26x(void *unused, void *data)
  951. {
  952. UNUSED_PARAMETER(unused);
  953. struct vt_encoder_type_data *type_data = data;
  954. obs_properties_t *props = obs_properties_create();
  955. obs_property_t *p;
  956. p = obs_properties_add_list(props, "rate_control", TEXT_RATE_CONTROL,
  957. OBS_COMBO_TYPE_LIST,
  958. OBS_COMBO_FORMAT_STRING);
  959. if (__builtin_available(macOS 13.0, *))
  960. if (type_data->hardware_accelerated
  961. #ifndef __aarch64__
  962. && (os_get_emulation_status() == true)
  963. #endif
  964. )
  965. obs_property_list_add_string(p, "CBR", "CBR");
  966. obs_property_list_add_string(p, "ABR", "ABR");
  967. if (type_data->hardware_accelerated
  968. #ifndef __aarch64__
  969. && (os_get_emulation_status() == true)
  970. #endif
  971. )
  972. obs_property_list_add_string(p, "CRF", "CRF");
  973. obs_property_set_modified_callback(p,
  974. rate_control_limit_bitrate_modified);
  975. p = obs_properties_add_int(props, "bitrate", TEXT_BITRATE, 50, 10000000,
  976. 50);
  977. obs_property_int_set_suffix(p, " Kbps");
  978. obs_properties_add_int_slider(props, "quality", TEXT_QUALITY, 0, 100,
  979. 1);
  980. p = obs_properties_add_bool(props, "limit_bitrate",
  981. TEXT_USE_MAX_BITRATE);
  982. obs_property_set_modified_callback(p,
  983. rate_control_limit_bitrate_modified);
  984. p = obs_properties_add_int(props, "max_bitrate", TEXT_MAX_BITRATE, 50,
  985. 10000000, 50);
  986. obs_property_int_set_suffix(p, " Kbps");
  987. p = obs_properties_add_float(props, "max_bitrate_window",
  988. TEXT_MAX_BITRATE_WINDOW, 0.10f, 10.0f,
  989. 0.25f);
  990. obs_property_float_set_suffix(p, " s");
  991. p = obs_properties_add_int(props, "keyint_sec", TEXT_KEYINT_SEC, 0, 20,
  992. 1);
  993. obs_property_int_set_suffix(p, " s");
  994. p = obs_properties_add_list(props, "profile", TEXT_PROFILE,
  995. OBS_COMBO_TYPE_LIST,
  996. OBS_COMBO_FORMAT_STRING);
  997. if (type_data->codec_type == kCMVideoCodecType_H264) {
  998. obs_property_list_add_string(p, "baseline", "baseline");
  999. obs_property_list_add_string(p, "main", "main");
  1000. obs_property_list_add_string(p, "high", "high");
  1001. #ifdef ENABLE_HEVC
  1002. } else if (type_data->codec_type == kCMVideoCodecType_HEVC) {
  1003. obs_property_list_add_string(p, "main", "main");
  1004. obs_property_list_add_string(p, "main10", "main10");
  1005. if (__builtin_available(macOS 12.3, *)) {
  1006. obs_property_list_add_string(p, "main 4:2:2 10",
  1007. "main42210");
  1008. }
  1009. #endif
  1010. }
  1011. obs_properties_add_bool(props, "bframes", TEXT_BFRAMES);
  1012. return props;
  1013. }
  1014. static obs_properties_t *vt_properties_prores(void *unused, void *data)
  1015. {
  1016. UNUSED_PARAMETER(unused);
  1017. struct vt_encoder_type_data *type_data = data;
  1018. obs_properties_t *props = obs_properties_create();
  1019. obs_property_t *p;
  1020. p = obs_properties_add_list(props, "codec_type", TEXT_PRORES_CODEC,
  1021. OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT);
  1022. uint32_t codec_availability_flags = 0;
  1023. size_t size = 0;
  1024. struct vt_prores_encoder_data *encoder_list = NULL;
  1025. if (type_data->hardware_accelerated) {
  1026. size = vt_prores_hardware_encoder_list.num;
  1027. encoder_list = vt_prores_hardware_encoder_list.array;
  1028. } else {
  1029. size = vt_prores_software_encoder_list.num;
  1030. encoder_list = vt_prores_software_encoder_list.array;
  1031. }
  1032. for (size_t i = 0; i < size; ++i) {
  1033. switch (encoder_list[i].codec_type) {
  1034. case kCMVideoCodecType_AppleProRes422Proxy:
  1035. codec_availability_flags |= (1 << 0);
  1036. break;
  1037. case kCMVideoCodecType_AppleProRes422LT:
  1038. codec_availability_flags |= (1 << 1);
  1039. break;
  1040. case kCMVideoCodecType_AppleProRes422:
  1041. codec_availability_flags |= (1 << 2);
  1042. break;
  1043. case kCMVideoCodecType_AppleProRes422HQ:
  1044. codec_availability_flags |= (1 << 3);
  1045. break;
  1046. }
  1047. }
  1048. if (codec_availability_flags & (1 << 0))
  1049. obs_property_list_add_int(
  1050. p, obs_module_text("ProRes422Proxy"),
  1051. kCMVideoCodecType_AppleProRes422Proxy);
  1052. if (codec_availability_flags & (1 << 1))
  1053. obs_property_list_add_int(p, obs_module_text("ProRes422LT"),
  1054. kCMVideoCodecType_AppleProRes422LT);
  1055. if (codec_availability_flags & (1 << 2))
  1056. obs_property_list_add_int(p, obs_module_text("ProRes422"),
  1057. kCMVideoCodecType_AppleProRes422);
  1058. if (codec_availability_flags & (1 << 3))
  1059. obs_property_list_add_int(p, obs_module_text("ProRes422HQ"),
  1060. kCMVideoCodecType_AppleProRes422HQ);
  1061. return props;
  1062. }
  1063. static void vt_defaults(obs_data_t *settings, void *data)
  1064. {
  1065. struct vt_encoder_type_data *type_data = data;
  1066. obs_data_set_default_string(settings, "rate_control", "ABR");
  1067. if (__builtin_available(macOS 13.0, *))
  1068. if (type_data->hardware_accelerated
  1069. #ifndef __aarch64__
  1070. && (os_get_emulation_status() == true)
  1071. #endif
  1072. )
  1073. obs_data_set_default_string(settings, "rate_control",
  1074. "CBR");
  1075. obs_data_set_default_int(settings, "bitrate", 2500);
  1076. obs_data_set_default_int(settings, "quality", 60);
  1077. obs_data_set_default_bool(settings, "limit_bitrate", false);
  1078. obs_data_set_default_int(settings, "max_bitrate", 2500);
  1079. obs_data_set_default_double(settings, "max_bitrate_window", 1.5f);
  1080. obs_data_set_default_int(settings, "keyint_sec", 0);
  1081. obs_data_set_default_string(settings, "profile", "main");
  1082. obs_data_set_default_int(settings, "codec_type",
  1083. kCMVideoCodecType_AppleProRes422);
  1084. obs_data_set_default_bool(settings, "bframes", true);
  1085. }
  1086. static void vt_free_type_data(void *data)
  1087. {
  1088. struct vt_encoder_type_data *type_data = data;
  1089. bfree((char *)type_data->disp_name);
  1090. bfree((char *)type_data->id);
  1091. bfree(type_data);
  1092. }
  1093. static inline void
  1094. vt_add_prores_encoder_data_to_list(CFDictionaryRef encoder_dict,
  1095. FourCharCode codec_type)
  1096. {
  1097. struct vt_prores_encoder_data *encoder_data = NULL;
  1098. CFBooleanRef hardware_accelerated = CFDictionaryGetValue(
  1099. encoder_dict, kVTVideoEncoderList_IsHardwareAccelerated);
  1100. if (hardware_accelerated == kCFBooleanTrue)
  1101. encoder_data =
  1102. da_push_back_new(vt_prores_hardware_encoder_list);
  1103. else
  1104. encoder_data =
  1105. da_push_back_new(vt_prores_software_encoder_list);
  1106. encoder_data->encoder_id = CFDictionaryGetValue(
  1107. encoder_dict, kVTVideoEncoderList_EncoderID);
  1108. encoder_data->codec_type = codec_type;
  1109. }
  1110. static CFComparisonResult
  1111. compare_encoder_list(const void *left_val, const void *right_val, void *unused)
  1112. {
  1113. UNUSED_PARAMETER(unused);
  1114. CFDictionaryRef left = (CFDictionaryRef)left_val;
  1115. CFDictionaryRef right = (CFDictionaryRef)right_val;
  1116. CFNumberRef left_codec_num =
  1117. CFDictionaryGetValue(left, kVTVideoEncoderList_CodecType);
  1118. CFNumberRef right_codec_num =
  1119. CFDictionaryGetValue(right, kVTVideoEncoderList_CodecType);
  1120. CFComparisonResult result =
  1121. CFNumberCompare(left_codec_num, right_codec_num, NULL);
  1122. if (result != kCFCompareEqualTo)
  1123. return result;
  1124. CFBooleanRef left_hardware_accel = CFDictionaryGetValue(
  1125. left, kVTVideoEncoderList_IsHardwareAccelerated);
  1126. CFBooleanRef right_hardware_accel = CFDictionaryGetValue(
  1127. right, kVTVideoEncoderList_IsHardwareAccelerated);
  1128. if (left_hardware_accel == right_hardware_accel)
  1129. return kCFCompareEqualTo;
  1130. else if (left_hardware_accel == kCFBooleanTrue)
  1131. return kCFCompareGreaterThan;
  1132. else
  1133. return kCFCompareLessThan;
  1134. }
  1135. OBS_DECLARE_MODULE()
  1136. OBS_MODULE_USE_DEFAULT_LOCALE("mac-videotoolbox", "en-US")
  1137. bool obs_module_load(void)
  1138. {
  1139. struct obs_encoder_info info = {
  1140. .type = OBS_ENCODER_VIDEO,
  1141. .get_name = vt_getname,
  1142. .create = vt_create,
  1143. .destroy = vt_destroy,
  1144. .encode = vt_encode,
  1145. .update = vt_update,
  1146. .get_defaults2 = vt_defaults,
  1147. .get_extra_data = vt_extra_data,
  1148. .free_type_data = vt_free_type_data,
  1149. .caps = OBS_ENCODER_CAP_DYN_BITRATE,
  1150. };
  1151. da_init(vt_prores_hardware_encoder_list);
  1152. da_init(vt_prores_software_encoder_list);
  1153. CFArrayRef encoder_list_const;
  1154. VTCopyVideoEncoderList(NULL, &encoder_list_const);
  1155. CFIndex size = CFArrayGetCount(encoder_list_const);
  1156. CFMutableArrayRef encoder_list = CFArrayCreateMutableCopy(
  1157. kCFAllocatorDefault, size, encoder_list_const);
  1158. CFRelease(encoder_list_const);
  1159. CFArraySortValues(encoder_list, CFRangeMake(0, size),
  1160. &compare_encoder_list, NULL);
  1161. for (CFIndex i = 0; i < size; i++) {
  1162. CFDictionaryRef encoder_dict =
  1163. CFArrayGetValueAtIndex(encoder_list, i);
  1164. #define VT_DICTSTR(key, name) \
  1165. CFStringRef name##_ref = CFDictionaryGetValue(encoder_dict, key); \
  1166. CFIndex name##_len = \
  1167. CFStringGetMaximumSizeOfFileSystemRepresentation(name##_ref); \
  1168. char *name = bzalloc(name##_len + 1); \
  1169. CFStringGetFileSystemRepresentation(name##_ref, name, name##_len);
  1170. CMVideoCodecType codec_type = 0;
  1171. {
  1172. CFNumberRef codec_type_num = CFDictionaryGetValue(
  1173. encoder_dict, kVTVideoEncoderList_CodecType);
  1174. CFNumberGetValue(codec_type_num, kCFNumberSInt32Type,
  1175. &codec_type);
  1176. }
  1177. switch (codec_type) {
  1178. case kCMVideoCodecType_H264:
  1179. info.get_properties2 = vt_properties_h26x;
  1180. info.codec = "h264";
  1181. break;
  1182. #ifdef ENABLE_HEVC
  1183. case kCMVideoCodecType_HEVC:
  1184. info.get_properties2 = vt_properties_h26x;
  1185. info.codec = "hevc";
  1186. break;
  1187. #endif
  1188. // 422 is used as a marker for all ProRes types,
  1189. // since the type is stored as a profile
  1190. case kCMVideoCodecType_AppleProRes422:
  1191. info.get_properties2 = vt_properties_prores;
  1192. info.codec = "prores";
  1193. vt_add_prores_encoder_data_to_list(encoder_dict,
  1194. codec_type);
  1195. break;
  1196. case kCMVideoCodecType_AppleProRes422Proxy:
  1197. case kCMVideoCodecType_AppleProRes422LT:
  1198. case kCMVideoCodecType_AppleProRes422HQ:
  1199. vt_add_prores_encoder_data_to_list(encoder_dict,
  1200. codec_type);
  1201. continue;
  1202. default:
  1203. continue;
  1204. }
  1205. VT_DICTSTR(kVTVideoEncoderList_EncoderID, id);
  1206. VT_DICTSTR(kVTVideoEncoderList_DisplayName, disp_name);
  1207. CFBooleanRef hardware_ref = CFDictionaryGetValue(
  1208. encoder_dict,
  1209. kVTVideoEncoderList_IsHardwareAccelerated);
  1210. bool hardware_accelerated =
  1211. (hardware_ref) ? CFBooleanGetValue(hardware_ref)
  1212. : false;
  1213. info.id = id;
  1214. struct vt_encoder_type_data *type_data =
  1215. bzalloc(sizeof(struct vt_encoder_type_data));
  1216. type_data->disp_name = disp_name;
  1217. type_data->id = id;
  1218. type_data->codec_type = codec_type;
  1219. type_data->hardware_accelerated = hardware_accelerated;
  1220. info.type_data = type_data;
  1221. obs_register_encoder(&info);
  1222. #undef VT_DICTSTR
  1223. }
  1224. CFRelease(encoder_list);
  1225. VT_LOG(LOG_INFO, "Adding VideoToolbox encoders");
  1226. return true;
  1227. }
  1228. void obs_module_unload(void)
  1229. {
  1230. da_free(vt_prores_hardware_encoder_list);
  1231. da_free(vt_prores_software_encoder_list);
  1232. }