encoder.c 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996
  1. #include <obs-module.h>
  2. #include <util/darray.h>
  3. #include <CoreFoundation/CoreFoundation.h>
  4. #include <VideoToolbox/VideoToolbox.h>
  5. #include <VideoToolbox/VTVideoEncoderList.h>
  6. #include <CoreMedia/CoreMedia.h>
  7. #include <util/apple/cfstring-utils.h>
  8. #include <assert.h>
  9. #define VT_LOG(level, format, ...) \
  10. blog(level, "[VideoToolbox encoder]: " format, ##__VA_ARGS__)
  11. #define VT_LOG_ENCODER(encoder, level, format, ...) \
  12. blog(level, "[VideoToolbox %s: 'h264']: " format, \
  13. obs_encoder_get_name(encoder), ##__VA_ARGS__)
  14. #define VT_BLOG(level, format, ...) \
  15. VT_LOG_ENCODER(enc->encoder, level, format, ##__VA_ARGS__)
  16. // Clipped from NSApplication as it is in a ObjC header
  17. extern const double NSAppKitVersionNumber;
  18. #define NSAppKitVersionNumber10_8 1187
  19. #define APPLE_H264_ENC_ID_HW "com.apple.videotoolbox.videoencoder.h264.gva"
  20. #define APPLE_H264_ENC_ID_SW "com.apple.videotoolbox.videoencoder.h264"
  21. // Get around missing symbol on 10.8 during compilation
  22. enum { 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. const char *vt_encoder_id)
  402. {
  403. struct vt_h264_encoder *enc = bzalloc(sizeof(struct vt_h264_encoder));
  404. OSStatus code;
  405. enc->encoder = encoder;
  406. enc->vt_encoder_id = vt_encoder_id;
  407. update_params(enc, settings);
  408. STATUS_CHECK(CMSimpleQueueCreate(NULL, 100, &enc->queue));
  409. if (!create_encoder(enc))
  410. goto fail;
  411. dump_encoder_info(enc);
  412. return enc;
  413. fail:
  414. vt_h264_destroy(enc);
  415. return NULL;
  416. }
  417. static void *vt_h264_create_hw(obs_data_t *settings, obs_encoder_t *encoder)
  418. {
  419. return vt_h264_create(settings, encoder, APPLE_H264_ENC_ID_HW);
  420. }
  421. static void *vt_h264_create_sw(obs_data_t *settings, obs_encoder_t *encoder)
  422. {
  423. return vt_h264_create(settings, encoder, APPLE_H264_ENC_ID_SW);
  424. }
  425. static const uint8_t annexb_startcode[4] = {0, 0, 0, 1};
  426. static void packet_put(struct darray *packet, const uint8_t *buf, size_t size)
  427. {
  428. darray_push_back_array(sizeof(uint8_t), packet, buf, size);
  429. }
  430. static void packet_put_startcode(struct darray *packet, int size)
  431. {
  432. assert(size == 3 || size == 4);
  433. packet_put(packet, &annexb_startcode[4 - size], size);
  434. }
  435. static void convert_block_nals_to_annexb(struct vt_h264_encoder *enc,
  436. struct darray *packet,
  437. CMBlockBufferRef block,
  438. int nal_length_bytes)
  439. {
  440. size_t block_size;
  441. uint8_t *block_buf;
  442. CMBlockBufferGetDataPointer(block, 0, NULL, &block_size,
  443. (char **)&block_buf);
  444. size_t bytes_remaining = block_size;
  445. while (bytes_remaining > 0) {
  446. uint32_t nal_size;
  447. if (nal_length_bytes == 1)
  448. nal_size = block_buf[0];
  449. else if (nal_length_bytes == 2)
  450. nal_size = CFSwapInt16BigToHost(
  451. ((uint16_t *)block_buf)[0]);
  452. else if (nal_length_bytes == 4)
  453. nal_size = CFSwapInt32BigToHost(
  454. ((uint32_t *)block_buf)[0]);
  455. else
  456. return;
  457. bytes_remaining -= nal_length_bytes;
  458. block_buf += nal_length_bytes;
  459. if (bytes_remaining < nal_size) {
  460. VT_BLOG(LOG_ERROR, "invalid nal block");
  461. return;
  462. }
  463. packet_put_startcode(packet, 3);
  464. packet_put(packet, block_buf, nal_size);
  465. bytes_remaining -= nal_size;
  466. block_buf += nal_size;
  467. }
  468. }
  469. static bool handle_keyframe(struct vt_h264_encoder *enc,
  470. CMFormatDescriptionRef format_desc,
  471. size_t param_count, struct darray *packet,
  472. struct darray *extra_data)
  473. {
  474. OSStatus code;
  475. const uint8_t *param;
  476. size_t param_size;
  477. for (size_t i = 0; i < param_count; i++) {
  478. code = CMVideoFormatDescriptionGetH264ParameterSetAtIndex(
  479. format_desc, i, &param, &param_size, NULL, NULL);
  480. if (code != noErr) {
  481. log_osstatus(LOG_ERROR, enc,
  482. "getting NAL parameter "
  483. "at index",
  484. code);
  485. return false;
  486. }
  487. packet_put_startcode(packet, 4);
  488. packet_put(packet, param, param_size);
  489. }
  490. // if we were passed an extra_data array, fill it with
  491. // SPS, PPS, etc.
  492. if (extra_data != NULL)
  493. packet_put(extra_data, packet->array, packet->num);
  494. return true;
  495. }
  496. static bool convert_sample_to_annexb(struct vt_h264_encoder *enc,
  497. struct darray *packet,
  498. struct darray *extra_data,
  499. CMSampleBufferRef buffer, bool keyframe)
  500. {
  501. OSStatus code;
  502. CMFormatDescriptionRef format_desc =
  503. CMSampleBufferGetFormatDescription(buffer);
  504. size_t param_count;
  505. int nal_length_bytes;
  506. code = CMVideoFormatDescriptionGetH264ParameterSetAtIndex(
  507. format_desc, 0, NULL, NULL, &param_count, &nal_length_bytes);
  508. // it is not clear what errors this function can return
  509. // so we check the two most reasonable
  510. if (code == kCMFormatDescriptionBridgeError_InvalidParameter_ ||
  511. code == kCMFormatDescriptionError_InvalidParameter) {
  512. VT_BLOG(LOG_WARNING, "assuming 2 parameter sets "
  513. "and 4 byte NAL length header");
  514. param_count = 2;
  515. nal_length_bytes = 4;
  516. } else if (code != noErr) {
  517. log_osstatus(LOG_ERROR, enc,
  518. "getting parameter count from sample", code);
  519. return false;
  520. }
  521. if (keyframe &&
  522. !handle_keyframe(enc, format_desc, param_count, packet, extra_data))
  523. return false;
  524. CMBlockBufferRef block = CMSampleBufferGetDataBuffer(buffer);
  525. convert_block_nals_to_annexb(enc, packet, block, nal_length_bytes);
  526. return true;
  527. }
  528. static bool is_sample_keyframe(CMSampleBufferRef buffer)
  529. {
  530. CFArrayRef attachments =
  531. CMSampleBufferGetSampleAttachmentsArray(buffer, false);
  532. if (attachments != NULL) {
  533. CFDictionaryRef attachment;
  534. CFBooleanRef has_dependencies;
  535. attachment =
  536. (CFDictionaryRef)CFArrayGetValueAtIndex(attachments, 0);
  537. has_dependencies = (CFBooleanRef)CFDictionaryGetValue(
  538. attachment, kCMSampleAttachmentKey_DependsOnOthers);
  539. return has_dependencies == kCFBooleanFalse;
  540. }
  541. return false;
  542. }
  543. static bool parse_sample(struct vt_h264_encoder *enc, CMSampleBufferRef buffer,
  544. struct encoder_packet *packet, CMTime off)
  545. {
  546. CMTime pts = CMSampleBufferGetPresentationTimeStamp(buffer);
  547. CMTime dts = CMSampleBufferGetDecodeTimeStamp(buffer);
  548. pts = CMTimeMultiplyByFloat64(pts,
  549. ((Float64)enc->fps_num / enc->fps_den));
  550. dts = CMTimeMultiplyByFloat64(dts,
  551. ((Float64)enc->fps_num / enc->fps_den));
  552. // imitate x264's negative dts when bframes might have pts < dts
  553. if (enc->bframes)
  554. dts = CMTimeSubtract(dts, off);
  555. bool keyframe = is_sample_keyframe(buffer);
  556. da_resize(enc->packet_data, 0);
  557. // If we are still looking for extra data
  558. struct darray *extra_data = NULL;
  559. if (enc->extra_data.num == 0)
  560. extra_data = &enc->extra_data.da;
  561. if (!convert_sample_to_annexb(enc, &enc->packet_data.da, extra_data,
  562. buffer, keyframe))
  563. goto fail;
  564. packet->type = OBS_ENCODER_VIDEO;
  565. packet->pts = (int64_t)(CMTimeGetSeconds(pts));
  566. packet->dts = (int64_t)(CMTimeGetSeconds(dts));
  567. packet->data = enc->packet_data.array;
  568. packet->size = enc->packet_data.num;
  569. packet->keyframe = keyframe;
  570. CFRelease(buffer);
  571. return true;
  572. fail:
  573. CFRelease(buffer);
  574. return false;
  575. }
  576. bool get_cached_pixel_buffer(struct vt_h264_encoder *enc, CVPixelBufferRef *buf)
  577. {
  578. OSStatus code;
  579. CVPixelBufferPoolRef pool =
  580. VTCompressionSessionGetPixelBufferPool(enc->session);
  581. if (!pool)
  582. return kCVReturnError;
  583. CVPixelBufferRef pixbuf;
  584. STATUS_CHECK(CVPixelBufferPoolCreatePixelBuffer(NULL, pool, &pixbuf));
  585. // Why aren't these already set on the pixel buffer?
  586. // I would have expected pixel buffers from the session's
  587. // pool to have the correct color space stuff set
  588. CFStringRef matrix = obs_to_vt_colorspace(enc->colorspace);
  589. CVBufferSetAttachment(pixbuf, kCVImageBufferYCbCrMatrixKey, matrix,
  590. kCVAttachmentMode_ShouldPropagate);
  591. CVBufferSetAttachment(pixbuf, kCVImageBufferColorPrimariesKey,
  592. kCVImageBufferColorPrimaries_ITU_R_709_2,
  593. kCVAttachmentMode_ShouldPropagate);
  594. CVBufferSetAttachment(pixbuf, kCVImageBufferTransferFunctionKey,
  595. kCVImageBufferTransferFunction_ITU_R_709_2,
  596. kCVAttachmentMode_ShouldPropagate);
  597. *buf = pixbuf;
  598. return true;
  599. fail:
  600. return false;
  601. }
  602. static bool vt_h264_encode(void *data, struct encoder_frame *frame,
  603. struct encoder_packet *packet, bool *received_packet)
  604. {
  605. struct vt_h264_encoder *enc = data;
  606. OSStatus code;
  607. CMTime dur = CMTimeMake(enc->fps_den, enc->fps_num);
  608. CMTime off = CMTimeMultiply(dur, 2);
  609. CMTime pts = CMTimeMultiply(dur, frame->pts);
  610. CVPixelBufferRef pixbuf = NULL;
  611. if (!get_cached_pixel_buffer(enc, &pixbuf)) {
  612. VT_BLOG(LOG_ERROR, "Unable to create pixel buffer");
  613. goto fail;
  614. }
  615. STATUS_CHECK(CVPixelBufferLockBaseAddress(pixbuf, 0));
  616. for (int i = 0; i < MAX_AV_PLANES; i++) {
  617. if (frame->data[i] == NULL)
  618. break;
  619. uint8_t *p = (uint8_t *)CVPixelBufferGetBaseAddressOfPlane(
  620. pixbuf, i);
  621. uint8_t *f = frame->data[i];
  622. size_t plane_linesize =
  623. CVPixelBufferGetBytesPerRowOfPlane(pixbuf, i);
  624. size_t plane_height = CVPixelBufferGetHeightOfPlane(pixbuf, i);
  625. for (size_t j = 0; j < plane_height; j++) {
  626. memcpy(p, f, frame->linesize[i]);
  627. p += plane_linesize;
  628. f += frame->linesize[i];
  629. }
  630. }
  631. STATUS_CHECK(CVPixelBufferUnlockBaseAddress(pixbuf, 0));
  632. STATUS_CHECK(VTCompressionSessionEncodeFrame(enc->session, pixbuf, pts,
  633. dur, NULL, pixbuf, NULL));
  634. CMSampleBufferRef buffer =
  635. (CMSampleBufferRef)CMSimpleQueueDequeue(enc->queue);
  636. // No samples waiting in the queue
  637. if (buffer == NULL)
  638. return true;
  639. *received_packet = true;
  640. return parse_sample(enc, buffer, packet, off);
  641. fail:
  642. return false;
  643. }
  644. #undef STATUS_CHECK
  645. #undef CFNUM_INT
  646. static bool vt_h264_extra_data(void *data, uint8_t **extra_data, size_t *size)
  647. {
  648. struct vt_h264_encoder *enc = (struct vt_h264_encoder *)data;
  649. *extra_data = enc->extra_data.array;
  650. *size = enc->extra_data.num;
  651. return true;
  652. }
  653. static const char *vt_h264_getname_hw(void *unused)
  654. {
  655. UNUSED_PARAMETER(unused);
  656. return obs_module_text("VTH264EncHW");
  657. }
  658. static const char *vt_h264_getname_sw(void *unused)
  659. {
  660. UNUSED_PARAMETER(unused);
  661. return obs_module_text("VTH264EncSW");
  662. }
  663. #define TEXT_VT_ENCODER obs_module_text("VTEncoder")
  664. #define TEXT_BITRATE obs_module_text("Bitrate")
  665. #define TEXT_USE_MAX_BITRATE obs_module_text("UseMaxBitrate")
  666. #define TEXT_MAX_BITRATE obs_module_text("MaxBitrate")
  667. #define TEXT_MAX_BITRATE_WINDOW obs_module_text("MaxBitrateWindow")
  668. #define TEXT_KEYINT_SEC obs_module_text("KeyframeIntervalSec")
  669. #define TEXT_PROFILE obs_module_text("Profile")
  670. #define TEXT_NONE obs_module_text("None")
  671. #define TEXT_DEFAULT obs_module_text("DefaultEncoder")
  672. #define TEXT_BFRAMES obs_module_text("UseBFrames")
  673. static bool limit_bitrate_modified(obs_properties_t *ppts, obs_property_t *p,
  674. obs_data_t *settings)
  675. {
  676. bool use_max_bitrate = obs_data_get_bool(settings, "limit_bitrate");
  677. p = obs_properties_get(ppts, "max_bitrate");
  678. obs_property_set_visible(p, use_max_bitrate);
  679. p = obs_properties_get(ppts, "max_bitrate_window");
  680. obs_property_set_visible(p, use_max_bitrate);
  681. return true;
  682. }
  683. static obs_properties_t *vt_h264_properties(void *unused)
  684. {
  685. UNUSED_PARAMETER(unused);
  686. obs_properties_t *props = obs_properties_create();
  687. obs_property_t *p;
  688. p = obs_properties_add_int(props, "bitrate", TEXT_BITRATE, 50, 10000000,
  689. 50);
  690. obs_property_int_set_suffix(p, " Kbps");
  691. p = obs_properties_add_bool(props, "limit_bitrate",
  692. TEXT_USE_MAX_BITRATE);
  693. obs_property_set_modified_callback(p, limit_bitrate_modified);
  694. p = obs_properties_add_int(props, "max_bitrate", TEXT_MAX_BITRATE, 50,
  695. 10000000, 50);
  696. obs_property_int_set_suffix(p, " Kbps");
  697. obs_properties_add_float(props, "max_bitrate_window",
  698. TEXT_MAX_BITRATE_WINDOW, 0.10f, 10.0f, 0.25f);
  699. obs_properties_add_int(props, "keyint_sec", TEXT_KEYINT_SEC, 0, 20, 1);
  700. p = obs_properties_add_list(props, "profile", TEXT_PROFILE,
  701. OBS_COMBO_TYPE_LIST,
  702. OBS_COMBO_FORMAT_STRING);
  703. obs_property_list_add_string(p, TEXT_NONE, "");
  704. obs_property_list_add_string(p, "baseline", "baseline");
  705. obs_property_list_add_string(p, "main", "main");
  706. obs_property_list_add_string(p, "high", "high");
  707. obs_properties_add_bool(props, "bframes", TEXT_BFRAMES);
  708. return props;
  709. }
  710. static void vt_h264_defaults(obs_data_t *settings)
  711. {
  712. obs_data_set_default_int(settings, "bitrate", 2500);
  713. obs_data_set_default_bool(settings, "limit_bitrate", false);
  714. obs_data_set_default_int(settings, "max_bitrate", 2500);
  715. obs_data_set_default_double(settings, "max_bitrate_window", 1.5f);
  716. obs_data_set_default_int(settings, "keyint_sec", 0);
  717. obs_data_set_default_string(settings, "profile", "");
  718. obs_data_set_default_bool(settings, "bframes", true);
  719. }
  720. OBS_DECLARE_MODULE()
  721. OBS_MODULE_USE_DEFAULT_LOCALE("mac-h264", "en-US")
  722. void encoder_list_create()
  723. {
  724. CFArrayRef encoder_list;
  725. VTCopyVideoEncoderList(NULL, &encoder_list);
  726. CFIndex size = CFArrayGetCount(encoder_list);
  727. for (CFIndex i = 0; i < size; i++) {
  728. CFDictionaryRef encoder_dict =
  729. CFArrayGetValueAtIndex(encoder_list, i);
  730. #define VT_DICTSTR(key, name) \
  731. CFStringRef name##_ref = CFDictionaryGetValue(encoder_dict, key); \
  732. CFIndex name##_len = CFStringGetLength(name##_ref); \
  733. char *name = bzalloc(name##_len + 1); \
  734. CFStringGetFileSystemRepresentation(name##_ref, name, name##_len);
  735. VT_DICTSTR(kVTVideoEncoderList_CodecName, codec_name);
  736. if (strcmp("H.264", codec_name) != 0) {
  737. bfree(codec_name);
  738. continue;
  739. }
  740. VT_DICTSTR(kVTVideoEncoderList_EncoderName, name);
  741. VT_DICTSTR(kVTVideoEncoderList_EncoderID, id);
  742. VT_DICTSTR(kVTVideoEncoderList_DisplayName, disp_name);
  743. struct vt_encoder enc = {
  744. .name = name,
  745. .id = id,
  746. .disp_name = disp_name,
  747. .codec_name = codec_name,
  748. };
  749. da_push_back(vt_encoders, &enc);
  750. #undef VT_DICTSTR
  751. }
  752. }
  753. void encoder_list_destroy()
  754. {
  755. for (size_t i = 0; i < vt_encoders.num; i++) {
  756. bfree((char *)vt_encoders.array[i].name);
  757. bfree((char *)vt_encoders.array[i].id);
  758. bfree((char *)vt_encoders.array[i].codec_name);
  759. bfree((char *)vt_encoders.array[i].disp_name);
  760. }
  761. da_free(vt_encoders);
  762. }
  763. void register_encoders()
  764. {
  765. struct obs_encoder_info info = {
  766. .type = OBS_ENCODER_VIDEO,
  767. .codec = "h264",
  768. .destroy = vt_h264_destroy,
  769. .encode = vt_h264_encode,
  770. .update = vt_h264_update,
  771. .get_properties = vt_h264_properties,
  772. .get_defaults = vt_h264_defaults,
  773. .get_video_info = vt_h264_video_info,
  774. .get_extra_data = vt_h264_extra_data,
  775. .caps = OBS_ENCODER_CAP_DYN_BITRATE,
  776. };
  777. for (size_t i = 0; i < vt_encoders.num; i++) {
  778. if (strcmp(vt_encoders.array[i].id, APPLE_H264_ENC_ID_HW) ==
  779. 0) {
  780. info.id = "vt_h264_hw";
  781. info.get_name = vt_h264_getname_hw;
  782. info.create = vt_h264_create_hw;
  783. obs_register_encoder(&info);
  784. } else if (strcmp(vt_encoders.array[i].id,
  785. APPLE_H264_ENC_ID_SW) == 0) {
  786. info.id = "vt_h264_sw";
  787. info.get_name = vt_h264_getname_sw;
  788. info.create = vt_h264_create_sw;
  789. obs_register_encoder(&info);
  790. }
  791. }
  792. }
  793. bool obs_module_load(void)
  794. {
  795. if (!is_appkit10_9_or_greater()) {
  796. VT_LOG(LOG_WARNING, "Not adding VideoToolbox H264 encoder; "
  797. "AppKit must be version 10.9 or greater");
  798. return false;
  799. }
  800. encoder_list_create();
  801. register_encoders();
  802. VT_LOG(LOG_INFO, "Adding VideoToolbox H264 encoders");
  803. return true;
  804. }
  805. void obs_module_unload(void)
  806. {
  807. encoder_list_destroy();
  808. }