encoder.c 28 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013
  1. #include <obs-module.h>
  2. #include <util/darray.h>
  3. #include <obs-avc.h>
  4. #include <CoreFoundation/CoreFoundation.h>
  5. #include <VideoToolbox/VideoToolbox.h>
  6. #include <VideoToolbox/VTVideoEncoderList.h>
  7. #include <CoreMedia/CoreMedia.h>
  8. #include <util/apple/cfstring-utils.h>
  9. #include <assert.h>
  10. #define VT_LOG(level, format, ...) \
  11. blog(level, "[VideoToolbox encoder]: " format, ##__VA_ARGS__)
  12. #define VT_LOG_ENCODER(encoder, level, format, ...) \
  13. blog(level, "[VideoToolbox %s: 'h264']: " format, \
  14. obs_encoder_get_name(encoder), ##__VA_ARGS__)
  15. #define VT_BLOG(level, format, ...) \
  16. VT_LOG_ENCODER(enc->encoder, level, format, ##__VA_ARGS__)
  17. // Clipped from NSApplication as it is in a ObjC header
  18. extern const double NSAppKitVersionNumber;
  19. #define NSAppKitVersionNumber10_8 1187
  20. // Get around missing symbol on 10.8 during compilation
  21. enum {
  22. kCMFormatDescriptionBridgeError_InvalidParameter_ = -12712,
  23. };
  24. static bool is_appkit10_9_or_greater()
  25. {
  26. return floor(NSAppKitVersionNumber) > NSAppKitVersionNumber10_8;
  27. }
  28. static DARRAY(struct vt_encoder {
  29. const char *name;
  30. const char *disp_name;
  31. const char *id;
  32. const char *codec_name;
  33. }) vt_encoders;
  34. struct vt_h264_encoder {
  35. obs_encoder_t *encoder;
  36. const char *vt_encoder_id;
  37. uint32_t width;
  38. uint32_t height;
  39. uint32_t keyint;
  40. uint32_t fps_num;
  41. uint32_t fps_den;
  42. uint32_t bitrate;
  43. bool limit_bitrate;
  44. uint32_t rc_max_bitrate;
  45. float rc_max_bitrate_window;
  46. const char *profile;
  47. bool bframes;
  48. enum video_format obs_pix_fmt;
  49. int vt_pix_fmt;
  50. enum video_colorspace colorspace;
  51. bool fullrange;
  52. VTCompressionSessionRef session;
  53. CMSimpleQueueRef queue;
  54. bool hw_enc;
  55. DARRAY(uint8_t) packet_data;
  56. DARRAY(uint8_t) extra_data;
  57. };
  58. static void log_osstatus(int log_level, struct vt_h264_encoder *enc,
  59. const char *context, OSStatus code)
  60. {
  61. char *c_str = NULL;
  62. CFErrorRef err = CFErrorCreate(kCFAllocatorDefault,
  63. kCFErrorDomainOSStatus, code, NULL);
  64. CFStringRef str = CFErrorCopyDescription(err);
  65. c_str = cfstr_copy_cstr(str, kCFStringEncodingUTF8);
  66. if (c_str) {
  67. if (enc)
  68. VT_BLOG(log_level, "Error in %s: %s", context, c_str);
  69. else
  70. VT_LOG(log_level, "Error in %s: %s", context, c_str);
  71. }
  72. bfree(c_str);
  73. CFRelease(str);
  74. CFRelease(err);
  75. }
  76. static CFStringRef obs_to_vt_profile(const char *profile)
  77. {
  78. if (strcmp(profile, "baseline") == 0)
  79. return kVTProfileLevel_H264_Baseline_AutoLevel;
  80. else if (strcmp(profile, "main") == 0)
  81. return kVTProfileLevel_H264_Main_AutoLevel;
  82. else if (strcmp(profile, "high") == 0)
  83. return kVTProfileLevel_H264_High_AutoLevel;
  84. else
  85. return kVTProfileLevel_H264_Main_AutoLevel;
  86. }
  87. static CFStringRef obs_to_vt_colorspace(enum video_colorspace cs)
  88. {
  89. if (cs == VIDEO_CS_709)
  90. return kCVImageBufferYCbCrMatrix_ITU_R_709_2;
  91. else if (cs == VIDEO_CS_601)
  92. return kCVImageBufferYCbCrMatrix_ITU_R_601_4;
  93. return NULL;
  94. }
  95. #define STATUS_CHECK(c) \
  96. code = c; \
  97. if (code) { \
  98. log_osstatus(LOG_ERROR, enc, #c, code); \
  99. goto fail; \
  100. }
  101. #define SESSION_CHECK(x) \
  102. if ((code = (x)) != noErr) \
  103. return code;
  104. static OSStatus session_set_prop_int(VTCompressionSessionRef session,
  105. CFStringRef key, int32_t val)
  106. {
  107. CFNumberRef n = CFNumberCreate(NULL, kCFNumberSInt32Type, &val);
  108. OSStatus code = VTSessionSetProperty(session, key, n);
  109. CFRelease(n);
  110. return code;
  111. }
  112. static OSStatus session_set_prop_str(VTCompressionSessionRef session,
  113. CFStringRef key, char *val)
  114. {
  115. CFStringRef s = CFStringCreateWithFileSystemRepresentation(NULL, val);
  116. OSStatus code = VTSessionSetProperty(session, key, s);
  117. CFRelease(s);
  118. return code;
  119. }
  120. static OSStatus session_set_prop(VTCompressionSessionRef session,
  121. CFStringRef key, CFTypeRef val)
  122. {
  123. return VTSessionSetProperty(session, key, val);
  124. }
  125. static OSStatus session_set_bitrate(VTCompressionSessionRef session,
  126. int new_bitrate, bool limit_bitrate,
  127. int max_bitrate, float max_bitrate_window)
  128. {
  129. OSStatus code;
  130. SESSION_CHECK(session_set_prop_int(
  131. session, kVTCompressionPropertyKey_AverageBitRate,
  132. new_bitrate * 1000));
  133. if (limit_bitrate) {
  134. int32_t cpb_size = max_bitrate * 125 * max_bitrate_window;
  135. CFNumberRef cf_cpb_size =
  136. CFNumberCreate(NULL, kCFNumberIntType, &cpb_size);
  137. CFNumberRef cf_cpb_window_s = CFNumberCreate(
  138. NULL, kCFNumberFloatType, &max_bitrate_window);
  139. CFMutableArrayRef rate_control = CFArrayCreateMutable(
  140. kCFAllocatorDefault, 2, &kCFTypeArrayCallBacks);
  141. CFArrayAppendValue(rate_control, cf_cpb_size);
  142. CFArrayAppendValue(rate_control, cf_cpb_window_s);
  143. code = session_set_prop(
  144. session, kVTCompressionPropertyKey_DataRateLimits,
  145. rate_control);
  146. CFRelease(cf_cpb_size);
  147. CFRelease(cf_cpb_window_s);
  148. CFRelease(rate_control);
  149. if (code == kVTPropertyNotSupportedErr) {
  150. log_osstatus(LOG_WARNING, NULL,
  151. "setting DataRateLimits on session", code);
  152. return noErr;
  153. }
  154. }
  155. return noErr;
  156. }
  157. static OSStatus session_set_colorspace(VTCompressionSessionRef session,
  158. enum video_colorspace cs)
  159. {
  160. CFStringRef matrix = obs_to_vt_colorspace(cs);
  161. OSStatus code;
  162. if (matrix != NULL) {
  163. SESSION_CHECK(session_set_prop(
  164. session, kVTCompressionPropertyKey_ColorPrimaries,
  165. kCVImageBufferColorPrimaries_ITU_R_709_2));
  166. SESSION_CHECK(session_set_prop(
  167. session, kVTCompressionPropertyKey_TransferFunction,
  168. kCVImageBufferTransferFunction_ITU_R_709_2));
  169. SESSION_CHECK(session_set_prop(
  170. session, kVTCompressionPropertyKey_YCbCrMatrix,
  171. matrix));
  172. }
  173. return noErr;
  174. }
  175. #undef SESSION_CHECK
  176. void sample_encoded_callback(void *data, void *source, OSStatus status,
  177. VTEncodeInfoFlags info_flags,
  178. CMSampleBufferRef buffer)
  179. {
  180. UNUSED_PARAMETER(status);
  181. UNUSED_PARAMETER(info_flags);
  182. CMSimpleQueueRef queue = data;
  183. CVPixelBufferRef pixbuf = source;
  184. if (buffer != NULL) {
  185. CFRetain(buffer);
  186. CMSimpleQueueEnqueue(queue, buffer);
  187. }
  188. CFRelease(pixbuf);
  189. }
  190. #define ENCODER_ID kVTVideoEncoderSpecification_EncoderID
  191. #define ENABLE_HW_ACCEL \
  192. kVTVideoEncoderSpecification_EnableHardwareAcceleratedVideoEncoder
  193. #define REQUIRE_HW_ACCEL \
  194. kVTVideoEncoderSpecification_RequireHardwareAcceleratedVideoEncoder
  195. static inline CFMutableDictionaryRef
  196. create_encoder_spec(const char *vt_encoder_id)
  197. {
  198. CFMutableDictionaryRef encoder_spec = CFDictionaryCreateMutable(
  199. kCFAllocatorDefault, 3, &kCFTypeDictionaryKeyCallBacks,
  200. &kCFTypeDictionaryValueCallBacks);
  201. CFStringRef id =
  202. CFStringCreateWithFileSystemRepresentation(NULL, vt_encoder_id);
  203. CFDictionaryAddValue(encoder_spec, ENCODER_ID, id);
  204. CFRelease(id);
  205. CFDictionaryAddValue(encoder_spec, ENABLE_HW_ACCEL, kCFBooleanTrue);
  206. CFDictionaryAddValue(encoder_spec, REQUIRE_HW_ACCEL, kCFBooleanFalse);
  207. return encoder_spec;
  208. }
  209. #undef ENCODER_ID
  210. #undef REQUIRE_HW_ACCEL
  211. #undef ENABLE_HW_ACCEL
  212. static inline CFMutableDictionaryRef
  213. create_pixbuf_spec(struct vt_h264_encoder *enc)
  214. {
  215. CFMutableDictionaryRef pixbuf_spec = CFDictionaryCreateMutable(
  216. kCFAllocatorDefault, 3, &kCFTypeDictionaryKeyCallBacks,
  217. &kCFTypeDictionaryValueCallBacks);
  218. CFNumberRef n =
  219. CFNumberCreate(NULL, kCFNumberSInt32Type, &enc->vt_pix_fmt);
  220. CFDictionaryAddValue(pixbuf_spec, kCVPixelBufferPixelFormatTypeKey, n);
  221. CFRelease(n);
  222. n = CFNumberCreate(NULL, kCFNumberSInt32Type, &enc->width);
  223. CFDictionaryAddValue(pixbuf_spec, kCVPixelBufferWidthKey, n);
  224. CFRelease(n);
  225. n = CFNumberCreate(NULL, kCFNumberSInt32Type, &enc->height);
  226. CFDictionaryAddValue(pixbuf_spec, kCVPixelBufferHeightKey, n);
  227. CFRelease(n);
  228. return pixbuf_spec;
  229. }
  230. static bool create_encoder(struct vt_h264_encoder *enc)
  231. {
  232. OSStatus code;
  233. VTCompressionSessionRef s;
  234. CFDictionaryRef encoder_spec = create_encoder_spec(enc->vt_encoder_id);
  235. CFDictionaryRef pixbuf_spec = create_pixbuf_spec(enc);
  236. STATUS_CHECK(VTCompressionSessionCreate(
  237. kCFAllocatorDefault, enc->width, enc->height,
  238. kCMVideoCodecType_H264, encoder_spec, pixbuf_spec, NULL,
  239. &sample_encoded_callback, enc->queue, &s));
  240. CFRelease(encoder_spec);
  241. CFRelease(pixbuf_spec);
  242. CFBooleanRef b = NULL;
  243. code = VTSessionCopyProperty(
  244. s,
  245. kVTCompressionPropertyKey_UsingHardwareAcceleratedVideoEncoder,
  246. NULL, &b);
  247. if (code == noErr && (enc->hw_enc = CFBooleanGetValue(b)))
  248. VT_BLOG(LOG_INFO, "session created with hardware encoding");
  249. else
  250. enc->hw_enc = false;
  251. if (b != NULL)
  252. CFRelease(b);
  253. STATUS_CHECK(session_set_prop_int(
  254. s, kVTCompressionPropertyKey_MaxKeyFrameIntervalDuration,
  255. enc->keyint));
  256. STATUS_CHECK(session_set_prop_int(
  257. s, kVTCompressionPropertyKey_MaxKeyFrameInterval,
  258. enc->keyint * ((float)enc->fps_num / enc->fps_den)));
  259. STATUS_CHECK(session_set_prop_int(
  260. s, kVTCompressionPropertyKey_ExpectedFrameRate,
  261. ceil((float)enc->fps_num / enc->fps_den)));
  262. STATUS_CHECK(session_set_prop(
  263. s, kVTCompressionPropertyKey_AllowFrameReordering,
  264. enc->bframes ? kCFBooleanTrue : kCFBooleanFalse));
  265. // This can fail depending on hardware configuration
  266. code = session_set_prop(s, kVTCompressionPropertyKey_RealTime,
  267. kCFBooleanTrue);
  268. if (code != noErr)
  269. log_osstatus(LOG_WARNING, enc,
  270. "setting "
  271. "kVTCompressionPropertyKey_RealTime, "
  272. "frame delay might be increased",
  273. code);
  274. STATUS_CHECK(session_set_prop(s, kVTCompressionPropertyKey_ProfileLevel,
  275. obs_to_vt_profile(enc->profile)));
  276. STATUS_CHECK(session_set_bitrate(s, enc->bitrate, enc->limit_bitrate,
  277. enc->rc_max_bitrate,
  278. enc->rc_max_bitrate_window));
  279. STATUS_CHECK(session_set_colorspace(s, enc->colorspace));
  280. STATUS_CHECK(VTCompressionSessionPrepareToEncodeFrames(s));
  281. enc->session = s;
  282. return true;
  283. fail:
  284. if (encoder_spec != NULL)
  285. CFRelease(encoder_spec);
  286. if (pixbuf_spec != NULL)
  287. CFRelease(pixbuf_spec);
  288. return false;
  289. }
  290. static void vt_h264_destroy(void *data)
  291. {
  292. struct vt_h264_encoder *enc = data;
  293. if (enc) {
  294. if (enc->session != NULL) {
  295. VTCompressionSessionInvalidate(enc->session);
  296. CFRelease(enc->session);
  297. }
  298. da_free(enc->packet_data);
  299. da_free(enc->extra_data);
  300. bfree(enc);
  301. }
  302. }
  303. static void dump_encoder_info(struct vt_h264_encoder *enc)
  304. {
  305. VT_BLOG(LOG_INFO,
  306. "settings:\n"
  307. "\tvt_encoder_id %s\n"
  308. "\tbitrate: %d (kbps)\n"
  309. "\tfps_num: %d\n"
  310. "\tfps_den: %d\n"
  311. "\twidth: %d\n"
  312. "\theight: %d\n"
  313. "\tkeyint: %d (s)\n"
  314. "\tlimit_bitrate: %s\n"
  315. "\trc_max_bitrate: %d (kbps)\n"
  316. "\trc_max_bitrate_window: %f (s)\n"
  317. "\thw_enc: %s\n"
  318. "\tprofile: %s\n",
  319. enc->vt_encoder_id, enc->bitrate, enc->fps_num, enc->fps_den,
  320. enc->width, enc->height, enc->keyint,
  321. enc->limit_bitrate ? "on" : "off", enc->rc_max_bitrate,
  322. enc->rc_max_bitrate_window, enc->hw_enc ? "on" : "off",
  323. (enc->profile != NULL && !!strlen(enc->profile)) ? enc->profile
  324. : "default");
  325. }
  326. static void vt_h264_video_info(void *data, struct video_scale_info *info)
  327. {
  328. struct vt_h264_encoder *enc = data;
  329. if (info->format == VIDEO_FORMAT_I420) {
  330. enc->obs_pix_fmt = info->format;
  331. enc->vt_pix_fmt =
  332. enc->fullrange
  333. ? kCVPixelFormatType_420YpCbCr8PlanarFullRange
  334. : kCVPixelFormatType_420YpCbCr8Planar;
  335. return;
  336. }
  337. if (info->format == VIDEO_FORMAT_I444)
  338. VT_BLOG(LOG_WARNING, "I444 color format not supported");
  339. // Anything else, return default
  340. enc->obs_pix_fmt = VIDEO_FORMAT_NV12;
  341. enc->vt_pix_fmt =
  342. enc->fullrange
  343. ? kCVPixelFormatType_420YpCbCr8BiPlanarFullRange
  344. : kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange;
  345. info->format = enc->obs_pix_fmt;
  346. }
  347. static void update_params(struct vt_h264_encoder *enc, obs_data_t *settings)
  348. {
  349. video_t *video = obs_encoder_video(enc->encoder);
  350. const struct video_output_info *voi = video_output_get_info(video);
  351. struct video_scale_info info = {.format = voi->format};
  352. enc->fullrange = voi->range == VIDEO_RANGE_FULL;
  353. // also sets the enc->vt_pix_fmt
  354. vt_h264_video_info(enc, &info);
  355. enc->colorspace = voi->colorspace;
  356. enc->width = obs_encoder_get_width(enc->encoder);
  357. enc->height = obs_encoder_get_height(enc->encoder);
  358. enc->fps_num = voi->fps_num;
  359. enc->fps_den = voi->fps_den;
  360. enc->keyint = (uint32_t)obs_data_get_int(settings, "keyint_sec");
  361. enc->bitrate = (uint32_t)obs_data_get_int(settings, "bitrate");
  362. enc->profile = obs_data_get_string(settings, "profile");
  363. enc->limit_bitrate = obs_data_get_bool(settings, "limit_bitrate");
  364. enc->rc_max_bitrate = obs_data_get_int(settings, "max_bitrate");
  365. enc->rc_max_bitrate_window =
  366. obs_data_get_double(settings, "max_bitrate_window");
  367. enc->bframes = obs_data_get_bool(settings, "bframes");
  368. }
  369. static bool vt_h264_update(void *data, obs_data_t *settings)
  370. {
  371. struct vt_h264_encoder *enc = data;
  372. uint32_t old_bitrate = enc->bitrate;
  373. bool old_limit_bitrate = enc->limit_bitrate;
  374. update_params(enc, settings);
  375. if (old_bitrate == enc->bitrate &&
  376. old_limit_bitrate == enc->limit_bitrate)
  377. return true;
  378. OSStatus code = session_set_bitrate(enc->session, enc->bitrate,
  379. enc->limit_bitrate,
  380. enc->rc_max_bitrate,
  381. enc->rc_max_bitrate_window);
  382. if (code != noErr)
  383. VT_BLOG(LOG_WARNING, "failed to set bitrate to session");
  384. CFNumberRef n;
  385. VTSessionCopyProperty(enc->session,
  386. kVTCompressionPropertyKey_AverageBitRate, NULL,
  387. &n);
  388. uint32_t session_bitrate;
  389. CFNumberGetValue(n, kCFNumberIntType, &session_bitrate);
  390. CFRelease(n);
  391. if (session_bitrate == old_bitrate) {
  392. VT_BLOG(LOG_WARNING,
  393. "failed to update current session "
  394. " bitrate from %d->%d",
  395. old_bitrate, enc->bitrate);
  396. }
  397. dump_encoder_info(enc);
  398. return true;
  399. }
  400. static void *vt_h264_create(obs_data_t *settings, obs_encoder_t *encoder)
  401. {
  402. struct vt_h264_encoder *enc = bzalloc(sizeof(struct vt_h264_encoder));
  403. OSStatus code;
  404. enc->encoder = encoder;
  405. enc->vt_encoder_id = obs_encoder_get_id(encoder);
  406. update_params(enc, settings);
  407. STATUS_CHECK(CMSimpleQueueCreate(NULL, 100, &enc->queue));
  408. if (!create_encoder(enc))
  409. goto fail;
  410. dump_encoder_info(enc);
  411. return enc;
  412. fail:
  413. vt_h264_destroy(enc);
  414. return NULL;
  415. }
  416. static const uint8_t annexb_startcode[4] = {0, 0, 0, 1};
  417. static void packet_put(struct darray *packet, const uint8_t *buf, size_t size)
  418. {
  419. darray_push_back_array(sizeof(uint8_t), packet, buf, size);
  420. }
  421. static void packet_put_startcode(struct darray *packet, int size)
  422. {
  423. assert(size == 3 || size == 4);
  424. packet_put(packet, &annexb_startcode[4 - size], size);
  425. }
  426. static void convert_block_nals_to_annexb(struct vt_h264_encoder *enc,
  427. struct darray *packet,
  428. CMBlockBufferRef block,
  429. int nal_length_bytes)
  430. {
  431. size_t block_size;
  432. uint8_t *block_buf;
  433. CMBlockBufferGetDataPointer(block, 0, NULL, &block_size,
  434. (char **)&block_buf);
  435. size_t bytes_remaining = block_size;
  436. while (bytes_remaining > 0) {
  437. uint32_t nal_size;
  438. if (nal_length_bytes == 1)
  439. nal_size = block_buf[0];
  440. else if (nal_length_bytes == 2)
  441. nal_size = CFSwapInt16BigToHost(
  442. ((uint16_t *)block_buf)[0]);
  443. else if (nal_length_bytes == 4)
  444. nal_size = CFSwapInt32BigToHost(
  445. ((uint32_t *)block_buf)[0]);
  446. else
  447. return;
  448. bytes_remaining -= nal_length_bytes;
  449. block_buf += nal_length_bytes;
  450. if (bytes_remaining < nal_size) {
  451. VT_BLOG(LOG_ERROR, "invalid nal block");
  452. return;
  453. }
  454. packet_put_startcode(packet, 3);
  455. packet_put(packet, block_buf, nal_size);
  456. bytes_remaining -= nal_size;
  457. block_buf += nal_size;
  458. }
  459. }
  460. static bool handle_keyframe(struct vt_h264_encoder *enc,
  461. CMFormatDescriptionRef format_desc,
  462. size_t param_count, struct darray *packet,
  463. struct darray *extra_data)
  464. {
  465. OSStatus code;
  466. const uint8_t *param;
  467. size_t param_size;
  468. for (size_t i = 0; i < param_count; i++) {
  469. code = CMVideoFormatDescriptionGetH264ParameterSetAtIndex(
  470. format_desc, i, &param, &param_size, NULL, NULL);
  471. if (code != noErr) {
  472. log_osstatus(LOG_ERROR, enc,
  473. "getting NAL parameter "
  474. "at index",
  475. code);
  476. return false;
  477. }
  478. packet_put_startcode(packet, 4);
  479. packet_put(packet, param, param_size);
  480. }
  481. // if we were passed an extra_data array, fill it with
  482. // SPS, PPS, etc.
  483. if (extra_data != NULL)
  484. packet_put(extra_data, packet->array, packet->num);
  485. return true;
  486. }
  487. static bool convert_sample_to_annexb(struct vt_h264_encoder *enc,
  488. struct darray *packet,
  489. struct darray *extra_data,
  490. CMSampleBufferRef buffer, bool keyframe)
  491. {
  492. OSStatus code;
  493. CMFormatDescriptionRef format_desc =
  494. CMSampleBufferGetFormatDescription(buffer);
  495. size_t param_count;
  496. int nal_length_bytes;
  497. code = CMVideoFormatDescriptionGetH264ParameterSetAtIndex(
  498. format_desc, 0, NULL, NULL, &param_count, &nal_length_bytes);
  499. // it is not clear what errors this function can return
  500. // so we check the two most reasonable
  501. if (code == kCMFormatDescriptionBridgeError_InvalidParameter_ ||
  502. code == kCMFormatDescriptionError_InvalidParameter) {
  503. VT_BLOG(LOG_WARNING, "assuming 2 parameter sets "
  504. "and 4 byte NAL length header");
  505. param_count = 2;
  506. nal_length_bytes = 4;
  507. } else if (code != noErr) {
  508. log_osstatus(LOG_ERROR, enc,
  509. "getting parameter count from sample", code);
  510. return false;
  511. }
  512. if (keyframe &&
  513. !handle_keyframe(enc, format_desc, param_count, packet, extra_data))
  514. return false;
  515. CMBlockBufferRef block = CMSampleBufferGetDataBuffer(buffer);
  516. convert_block_nals_to_annexb(enc, packet, block, nal_length_bytes);
  517. return true;
  518. }
  519. static bool is_sample_keyframe(CMSampleBufferRef buffer)
  520. {
  521. CFArrayRef attachments =
  522. CMSampleBufferGetSampleAttachmentsArray(buffer, false);
  523. if (attachments != NULL) {
  524. CFDictionaryRef attachment;
  525. CFBooleanRef has_dependencies;
  526. attachment =
  527. (CFDictionaryRef)CFArrayGetValueAtIndex(attachments, 0);
  528. has_dependencies = (CFBooleanRef)CFDictionaryGetValue(
  529. attachment, kCMSampleAttachmentKey_DependsOnOthers);
  530. return has_dependencies == kCFBooleanFalse;
  531. }
  532. return false;
  533. }
  534. static bool parse_sample(struct vt_h264_encoder *enc, CMSampleBufferRef buffer,
  535. struct encoder_packet *packet, CMTime off)
  536. {
  537. int type;
  538. CMTime pts = CMSampleBufferGetPresentationTimeStamp(buffer);
  539. CMTime dts = CMSampleBufferGetDecodeTimeStamp(buffer);
  540. pts = CMTimeMultiplyByFloat64(pts,
  541. ((Float64)enc->fps_num / enc->fps_den));
  542. dts = CMTimeMultiplyByFloat64(dts,
  543. ((Float64)enc->fps_num / enc->fps_den));
  544. if (CMTIME_IS_INVALID(dts))
  545. dts = pts;
  546. // imitate x264's negative dts when bframes might have pts < dts
  547. else if (enc->bframes)
  548. dts = CMTimeSubtract(dts, off);
  549. bool keyframe = is_sample_keyframe(buffer);
  550. da_resize(enc->packet_data, 0);
  551. // If we are still looking for extra data
  552. struct darray *extra_data = NULL;
  553. if (enc->extra_data.num == 0)
  554. extra_data = &enc->extra_data.da;
  555. if (!convert_sample_to_annexb(enc, &enc->packet_data.da, extra_data,
  556. buffer, keyframe))
  557. goto fail;
  558. packet->type = OBS_ENCODER_VIDEO;
  559. packet->pts = (int64_t)(CMTimeGetSeconds(pts));
  560. packet->dts = (int64_t)(CMTimeGetSeconds(dts));
  561. packet->data = enc->packet_data.array;
  562. packet->size = enc->packet_data.num;
  563. packet->keyframe = keyframe;
  564. // VideoToolbox produces packets with priority lower than the RTMP code
  565. // expects, which causes it to be unable to recover from frame drops.
  566. // Fix this by manually adjusting the priority.
  567. uint8_t *start = enc->packet_data.array;
  568. uint8_t *end = start + enc->packet_data.num;
  569. start = (uint8_t *)obs_avc_find_startcode(start, end);
  570. while (true) {
  571. while (start < end && !*(start++))
  572. ;
  573. if (start == end)
  574. break;
  575. type = start[0] & 0x1F;
  576. if (type == OBS_NAL_SLICE_IDR || type == OBS_NAL_SLICE) {
  577. uint8_t prev_type = (start[0] >> 5) & 0x3;
  578. start[0] &= ~(3 << 5);
  579. if (type == OBS_NAL_SLICE_IDR)
  580. start[0] |= OBS_NAL_PRIORITY_HIGHEST << 5;
  581. else if (type == OBS_NAL_SLICE &&
  582. prev_type != OBS_NAL_PRIORITY_DISPOSABLE)
  583. start[0] |= OBS_NAL_PRIORITY_HIGH << 5;
  584. else
  585. start[0] |= prev_type << 5;
  586. }
  587. start = (uint8_t *)obs_avc_find_startcode(start, end);
  588. }
  589. CFRelease(buffer);
  590. return true;
  591. fail:
  592. CFRelease(buffer);
  593. return false;
  594. }
  595. bool get_cached_pixel_buffer(struct vt_h264_encoder *enc, CVPixelBufferRef *buf)
  596. {
  597. OSStatus code;
  598. CVPixelBufferPoolRef pool =
  599. VTCompressionSessionGetPixelBufferPool(enc->session);
  600. if (!pool)
  601. return kCVReturnError;
  602. CVPixelBufferRef pixbuf;
  603. STATUS_CHECK(CVPixelBufferPoolCreatePixelBuffer(NULL, pool, &pixbuf));
  604. // Why aren't these already set on the pixel buffer?
  605. // I would have expected pixel buffers from the session's
  606. // pool to have the correct color space stuff set
  607. CFStringRef matrix = obs_to_vt_colorspace(enc->colorspace);
  608. CVBufferSetAttachment(pixbuf, kCVImageBufferYCbCrMatrixKey, matrix,
  609. kCVAttachmentMode_ShouldPropagate);
  610. CVBufferSetAttachment(pixbuf, kCVImageBufferColorPrimariesKey,
  611. kCVImageBufferColorPrimaries_ITU_R_709_2,
  612. kCVAttachmentMode_ShouldPropagate);
  613. CVBufferSetAttachment(pixbuf, kCVImageBufferTransferFunctionKey,
  614. kCVImageBufferTransferFunction_ITU_R_709_2,
  615. kCVAttachmentMode_ShouldPropagate);
  616. *buf = pixbuf;
  617. return true;
  618. fail:
  619. return false;
  620. }
  621. static bool vt_h264_encode(void *data, struct encoder_frame *frame,
  622. struct encoder_packet *packet, bool *received_packet)
  623. {
  624. struct vt_h264_encoder *enc = data;
  625. OSStatus code;
  626. CMTime dur = CMTimeMake(enc->fps_den, enc->fps_num);
  627. CMTime off = CMTimeMultiply(dur, 2);
  628. CMTime pts = CMTimeMultiply(dur, frame->pts);
  629. CVPixelBufferRef pixbuf = NULL;
  630. if (!get_cached_pixel_buffer(enc, &pixbuf)) {
  631. VT_BLOG(LOG_ERROR, "Unable to create pixel buffer");
  632. goto fail;
  633. }
  634. STATUS_CHECK(CVPixelBufferLockBaseAddress(pixbuf, 0));
  635. for (int i = 0; i < MAX_AV_PLANES; i++) {
  636. if (frame->data[i] == NULL)
  637. break;
  638. uint8_t *p = (uint8_t *)CVPixelBufferGetBaseAddressOfPlane(
  639. pixbuf, i);
  640. uint8_t *f = frame->data[i];
  641. size_t plane_linesize =
  642. CVPixelBufferGetBytesPerRowOfPlane(pixbuf, i);
  643. size_t plane_height = CVPixelBufferGetHeightOfPlane(pixbuf, i);
  644. for (size_t j = 0; j < plane_height; j++) {
  645. memcpy(p, f, frame->linesize[i]);
  646. p += plane_linesize;
  647. f += frame->linesize[i];
  648. }
  649. }
  650. STATUS_CHECK(CVPixelBufferUnlockBaseAddress(pixbuf, 0));
  651. STATUS_CHECK(VTCompressionSessionEncodeFrame(enc->session, pixbuf, pts,
  652. dur, NULL, pixbuf, NULL));
  653. CMSampleBufferRef buffer =
  654. (CMSampleBufferRef)CMSimpleQueueDequeue(enc->queue);
  655. // No samples waiting in the queue
  656. if (buffer == NULL)
  657. return true;
  658. *received_packet = true;
  659. return parse_sample(enc, buffer, packet, off);
  660. fail:
  661. return false;
  662. }
  663. #undef STATUS_CHECK
  664. #undef CFNUM_INT
  665. static bool vt_h264_extra_data(void *data, uint8_t **extra_data, size_t *size)
  666. {
  667. struct vt_h264_encoder *enc = (struct vt_h264_encoder *)data;
  668. *extra_data = enc->extra_data.array;
  669. *size = enc->extra_data.num;
  670. return true;
  671. }
  672. static const char *vt_h264_getname(void *data)
  673. {
  674. const char *disp_name = vt_encoders.array[(int)data].disp_name;
  675. if (strcmp("Apple H.264 (HW)", disp_name) == 0) {
  676. return obs_module_text("VTH264EncHW");
  677. } else if (strcmp("Apple H.264 (SW)", disp_name) == 0) {
  678. return obs_module_text("VTH264EncSW");
  679. }
  680. return disp_name;
  681. }
  682. #define TEXT_VT_ENCODER obs_module_text("VTEncoder")
  683. #define TEXT_BITRATE obs_module_text("Bitrate")
  684. #define TEXT_USE_MAX_BITRATE obs_module_text("UseMaxBitrate")
  685. #define TEXT_MAX_BITRATE obs_module_text("MaxBitrate")
  686. #define TEXT_MAX_BITRATE_WINDOW obs_module_text("MaxBitrateWindow")
  687. #define TEXT_KEYINT_SEC obs_module_text("KeyframeIntervalSec")
  688. #define TEXT_PROFILE obs_module_text("Profile")
  689. #define TEXT_NONE obs_module_text("None")
  690. #define TEXT_DEFAULT obs_module_text("DefaultEncoder")
  691. #define TEXT_BFRAMES obs_module_text("UseBFrames")
  692. static bool limit_bitrate_modified(obs_properties_t *ppts, obs_property_t *p,
  693. obs_data_t *settings)
  694. {
  695. bool use_max_bitrate = obs_data_get_bool(settings, "limit_bitrate");
  696. p = obs_properties_get(ppts, "max_bitrate");
  697. obs_property_set_visible(p, use_max_bitrate);
  698. p = obs_properties_get(ppts, "max_bitrate_window");
  699. obs_property_set_visible(p, use_max_bitrate);
  700. return true;
  701. }
  702. static obs_properties_t *vt_h264_properties(void *unused)
  703. {
  704. UNUSED_PARAMETER(unused);
  705. obs_properties_t *props = obs_properties_create();
  706. obs_property_t *p;
  707. p = obs_properties_add_int(props, "bitrate", TEXT_BITRATE, 50, 10000000,
  708. 50);
  709. obs_property_int_set_suffix(p, " Kbps");
  710. p = obs_properties_add_bool(props, "limit_bitrate",
  711. TEXT_USE_MAX_BITRATE);
  712. obs_property_set_modified_callback(p, limit_bitrate_modified);
  713. p = obs_properties_add_int(props, "max_bitrate", TEXT_MAX_BITRATE, 50,
  714. 10000000, 50);
  715. obs_property_int_set_suffix(p, " Kbps");
  716. obs_properties_add_float(props, "max_bitrate_window",
  717. TEXT_MAX_BITRATE_WINDOW, 0.10f, 10.0f, 0.25f);
  718. obs_properties_add_int(props, "keyint_sec", TEXT_KEYINT_SEC, 0, 20, 1);
  719. p = obs_properties_add_list(props, "profile", TEXT_PROFILE,
  720. OBS_COMBO_TYPE_LIST,
  721. OBS_COMBO_FORMAT_STRING);
  722. obs_property_list_add_string(p, TEXT_NONE, "");
  723. obs_property_list_add_string(p, "baseline", "baseline");
  724. obs_property_list_add_string(p, "main", "main");
  725. obs_property_list_add_string(p, "high", "high");
  726. obs_properties_add_bool(props, "bframes", TEXT_BFRAMES);
  727. return props;
  728. }
  729. static void vt_h264_defaults(obs_data_t *settings)
  730. {
  731. obs_data_set_default_int(settings, "bitrate", 2500);
  732. obs_data_set_default_bool(settings, "limit_bitrate", false);
  733. obs_data_set_default_int(settings, "max_bitrate", 2500);
  734. obs_data_set_default_double(settings, "max_bitrate_window", 1.5f);
  735. obs_data_set_default_int(settings, "keyint_sec", 0);
  736. obs_data_set_default_string(settings, "profile", "");
  737. obs_data_set_default_bool(settings, "bframes", true);
  738. }
  739. OBS_DECLARE_MODULE()
  740. OBS_MODULE_USE_DEFAULT_LOCALE("mac-h264", "en-US")
  741. void encoder_list_create()
  742. {
  743. CFArrayRef encoder_list;
  744. VTCopyVideoEncoderList(NULL, &encoder_list);
  745. CFIndex size = CFArrayGetCount(encoder_list);
  746. for (CFIndex i = 0; i < size; i++) {
  747. CFDictionaryRef encoder_dict =
  748. CFArrayGetValueAtIndex(encoder_list, i);
  749. #define VT_DICTSTR(key, name) \
  750. CFStringRef name##_ref = CFDictionaryGetValue(encoder_dict, key); \
  751. CFIndex name##_len = CFStringGetLength(name##_ref); \
  752. char *name = bzalloc(name##_len + 1); \
  753. CFStringGetFileSystemRepresentation(name##_ref, name, name##_len);
  754. VT_DICTSTR(kVTVideoEncoderList_CodecName, codec_name);
  755. if (strcmp("H.264", codec_name) != 0) {
  756. bfree(codec_name);
  757. continue;
  758. }
  759. VT_DICTSTR(kVTVideoEncoderList_EncoderName, name);
  760. VT_DICTSTR(kVTVideoEncoderList_EncoderID, id);
  761. VT_DICTSTR(kVTVideoEncoderList_DisplayName, disp_name);
  762. struct vt_encoder enc = {
  763. .name = name,
  764. .id = id,
  765. .disp_name = disp_name,
  766. .codec_name = codec_name,
  767. };
  768. da_push_back(vt_encoders, &enc);
  769. #undef VT_DICTSTR
  770. }
  771. CFRelease(encoder_list);
  772. }
  773. void encoder_list_destroy()
  774. {
  775. for (size_t i = 0; i < vt_encoders.num; i++) {
  776. bfree((char *)vt_encoders.array[i].name);
  777. bfree((char *)vt_encoders.array[i].id);
  778. bfree((char *)vt_encoders.array[i].codec_name);
  779. bfree((char *)vt_encoders.array[i].disp_name);
  780. }
  781. da_free(vt_encoders);
  782. }
  783. void register_encoders()
  784. {
  785. struct obs_encoder_info info = {
  786. .type = OBS_ENCODER_VIDEO,
  787. .codec = "h264",
  788. .destroy = vt_h264_destroy,
  789. .encode = vt_h264_encode,
  790. .update = vt_h264_update,
  791. .get_properties = vt_h264_properties,
  792. .get_defaults = vt_h264_defaults,
  793. .get_video_info = vt_h264_video_info,
  794. .get_extra_data = vt_h264_extra_data,
  795. .caps = OBS_ENCODER_CAP_DYN_BITRATE,
  796. };
  797. for (size_t i = 0; i < vt_encoders.num; i++) {
  798. info.id = vt_encoders.array[i].id;
  799. info.type_data = (void *)i;
  800. info.get_name = vt_h264_getname;
  801. info.create = vt_h264_create;
  802. obs_register_encoder(&info);
  803. }
  804. }
  805. bool obs_module_load(void)
  806. {
  807. if (!is_appkit10_9_or_greater()) {
  808. VT_LOG(LOG_WARNING, "Not adding VideoToolbox H264 encoder; "
  809. "AppKit must be version 10.9 or greater");
  810. return false;
  811. }
  812. encoder_list_create();
  813. register_encoders();
  814. VT_LOG(LOG_INFO, "Adding VideoToolbox H264 encoders");
  815. return true;
  816. }
  817. void obs_module_unload(void)
  818. {
  819. encoder_list_destroy();
  820. }