encoder.c 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011
  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. // imitate x264's negative dts when bframes might have pts < dts
  545. if (enc->bframes)
  546. dts = CMTimeSubtract(dts, off);
  547. bool keyframe = is_sample_keyframe(buffer);
  548. da_resize(enc->packet_data, 0);
  549. // If we are still looking for extra data
  550. struct darray *extra_data = NULL;
  551. if (enc->extra_data.num == 0)
  552. extra_data = &enc->extra_data.da;
  553. if (!convert_sample_to_annexb(enc, &enc->packet_data.da, extra_data,
  554. buffer, keyframe))
  555. goto fail;
  556. packet->type = OBS_ENCODER_VIDEO;
  557. packet->pts = (int64_t)(CMTimeGetSeconds(pts));
  558. packet->dts = (int64_t)(CMTimeGetSeconds(dts));
  559. packet->data = enc->packet_data.array;
  560. packet->size = enc->packet_data.num;
  561. packet->keyframe = keyframe;
  562. // VideoToolbox produces packets with priority lower than the RTMP code
  563. // expects, which causes it to be unable to recover from frame drops.
  564. // Fix this by manually adjusting the priority.
  565. uint8_t *start = enc->packet_data.array;
  566. uint8_t *end = start + enc->packet_data.num;
  567. start = (uint8_t *)obs_avc_find_startcode(start, end);
  568. while (true) {
  569. while (start < end && !*(start++))
  570. ;
  571. if (start == end)
  572. break;
  573. type = start[0] & 0x1F;
  574. if (type == OBS_NAL_SLICE_IDR || type == OBS_NAL_SLICE) {
  575. uint8_t prev_type = (start[0] >> 5) & 0x3;
  576. start[0] &= ~(3 << 5);
  577. if (type == OBS_NAL_SLICE_IDR)
  578. start[0] |= OBS_NAL_PRIORITY_HIGHEST << 5;
  579. else if (type == OBS_NAL_SLICE &&
  580. prev_type != OBS_NAL_PRIORITY_DISPOSABLE)
  581. start[0] |= OBS_NAL_PRIORITY_HIGH << 5;
  582. else
  583. start[0] |= prev_type << 5;
  584. }
  585. start = (uint8_t *)obs_avc_find_startcode(start, end);
  586. }
  587. CFRelease(buffer);
  588. return true;
  589. fail:
  590. CFRelease(buffer);
  591. return false;
  592. }
  593. bool get_cached_pixel_buffer(struct vt_h264_encoder *enc, CVPixelBufferRef *buf)
  594. {
  595. OSStatus code;
  596. CVPixelBufferPoolRef pool =
  597. VTCompressionSessionGetPixelBufferPool(enc->session);
  598. if (!pool)
  599. return kCVReturnError;
  600. CVPixelBufferRef pixbuf;
  601. STATUS_CHECK(CVPixelBufferPoolCreatePixelBuffer(NULL, pool, &pixbuf));
  602. // Why aren't these already set on the pixel buffer?
  603. // I would have expected pixel buffers from the session's
  604. // pool to have the correct color space stuff set
  605. CFStringRef matrix = obs_to_vt_colorspace(enc->colorspace);
  606. CVBufferSetAttachment(pixbuf, kCVImageBufferYCbCrMatrixKey, matrix,
  607. kCVAttachmentMode_ShouldPropagate);
  608. CVBufferSetAttachment(pixbuf, kCVImageBufferColorPrimariesKey,
  609. kCVImageBufferColorPrimaries_ITU_R_709_2,
  610. kCVAttachmentMode_ShouldPropagate);
  611. CVBufferSetAttachment(pixbuf, kCVImageBufferTransferFunctionKey,
  612. kCVImageBufferTransferFunction_ITU_R_709_2,
  613. kCVAttachmentMode_ShouldPropagate);
  614. *buf = pixbuf;
  615. return true;
  616. fail:
  617. return false;
  618. }
  619. static bool vt_h264_encode(void *data, struct encoder_frame *frame,
  620. struct encoder_packet *packet, bool *received_packet)
  621. {
  622. struct vt_h264_encoder *enc = data;
  623. OSStatus code;
  624. CMTime dur = CMTimeMake(enc->fps_den, enc->fps_num);
  625. CMTime off = CMTimeMultiply(dur, 2);
  626. CMTime pts = CMTimeMultiply(dur, frame->pts);
  627. CVPixelBufferRef pixbuf = NULL;
  628. if (!get_cached_pixel_buffer(enc, &pixbuf)) {
  629. VT_BLOG(LOG_ERROR, "Unable to create pixel buffer");
  630. goto fail;
  631. }
  632. STATUS_CHECK(CVPixelBufferLockBaseAddress(pixbuf, 0));
  633. for (int i = 0; i < MAX_AV_PLANES; i++) {
  634. if (frame->data[i] == NULL)
  635. break;
  636. uint8_t *p = (uint8_t *)CVPixelBufferGetBaseAddressOfPlane(
  637. pixbuf, i);
  638. uint8_t *f = frame->data[i];
  639. size_t plane_linesize =
  640. CVPixelBufferGetBytesPerRowOfPlane(pixbuf, i);
  641. size_t plane_height = CVPixelBufferGetHeightOfPlane(pixbuf, i);
  642. for (size_t j = 0; j < plane_height; j++) {
  643. memcpy(p, f, frame->linesize[i]);
  644. p += plane_linesize;
  645. f += frame->linesize[i];
  646. }
  647. }
  648. STATUS_CHECK(CVPixelBufferUnlockBaseAddress(pixbuf, 0));
  649. STATUS_CHECK(VTCompressionSessionEncodeFrame(enc->session, pixbuf, pts,
  650. dur, NULL, pixbuf, NULL));
  651. CMSampleBufferRef buffer =
  652. (CMSampleBufferRef)CMSimpleQueueDequeue(enc->queue);
  653. // No samples waiting in the queue
  654. if (buffer == NULL)
  655. return true;
  656. *received_packet = true;
  657. return parse_sample(enc, buffer, packet, off);
  658. fail:
  659. return false;
  660. }
  661. #undef STATUS_CHECK
  662. #undef CFNUM_INT
  663. static bool vt_h264_extra_data(void *data, uint8_t **extra_data, size_t *size)
  664. {
  665. struct vt_h264_encoder *enc = (struct vt_h264_encoder *)data;
  666. *extra_data = enc->extra_data.array;
  667. *size = enc->extra_data.num;
  668. return true;
  669. }
  670. static const char *vt_h264_getname(void *data)
  671. {
  672. const char *disp_name = vt_encoders.array[(int)data].disp_name;
  673. if (strcmp("Apple H.264 (HW)", disp_name) == 0) {
  674. return obs_module_text("VTH264EncHW");
  675. } else if (strcmp("Apple H.264 (SW)", disp_name) == 0) {
  676. return obs_module_text("VTH264EncSW");
  677. }
  678. return disp_name;
  679. }
  680. #define TEXT_VT_ENCODER obs_module_text("VTEncoder")
  681. #define TEXT_BITRATE obs_module_text("Bitrate")
  682. #define TEXT_USE_MAX_BITRATE obs_module_text("UseMaxBitrate")
  683. #define TEXT_MAX_BITRATE obs_module_text("MaxBitrate")
  684. #define TEXT_MAX_BITRATE_WINDOW obs_module_text("MaxBitrateWindow")
  685. #define TEXT_KEYINT_SEC obs_module_text("KeyframeIntervalSec")
  686. #define TEXT_PROFILE obs_module_text("Profile")
  687. #define TEXT_NONE obs_module_text("None")
  688. #define TEXT_DEFAULT obs_module_text("DefaultEncoder")
  689. #define TEXT_BFRAMES obs_module_text("UseBFrames")
  690. static bool limit_bitrate_modified(obs_properties_t *ppts, obs_property_t *p,
  691. obs_data_t *settings)
  692. {
  693. bool use_max_bitrate = obs_data_get_bool(settings, "limit_bitrate");
  694. p = obs_properties_get(ppts, "max_bitrate");
  695. obs_property_set_visible(p, use_max_bitrate);
  696. p = obs_properties_get(ppts, "max_bitrate_window");
  697. obs_property_set_visible(p, use_max_bitrate);
  698. return true;
  699. }
  700. static obs_properties_t *vt_h264_properties(void *unused)
  701. {
  702. UNUSED_PARAMETER(unused);
  703. obs_properties_t *props = obs_properties_create();
  704. obs_property_t *p;
  705. p = obs_properties_add_int(props, "bitrate", TEXT_BITRATE, 50, 10000000,
  706. 50);
  707. obs_property_int_set_suffix(p, " Kbps");
  708. p = obs_properties_add_bool(props, "limit_bitrate",
  709. TEXT_USE_MAX_BITRATE);
  710. obs_property_set_modified_callback(p, limit_bitrate_modified);
  711. p = obs_properties_add_int(props, "max_bitrate", TEXT_MAX_BITRATE, 50,
  712. 10000000, 50);
  713. obs_property_int_set_suffix(p, " Kbps");
  714. obs_properties_add_float(props, "max_bitrate_window",
  715. TEXT_MAX_BITRATE_WINDOW, 0.10f, 10.0f, 0.25f);
  716. obs_properties_add_int(props, "keyint_sec", TEXT_KEYINT_SEC, 0, 20, 1);
  717. p = obs_properties_add_list(props, "profile", TEXT_PROFILE,
  718. OBS_COMBO_TYPE_LIST,
  719. OBS_COMBO_FORMAT_STRING);
  720. obs_property_list_add_string(p, TEXT_NONE, "");
  721. obs_property_list_add_string(p, "baseline", "baseline");
  722. obs_property_list_add_string(p, "main", "main");
  723. obs_property_list_add_string(p, "high", "high");
  724. obs_properties_add_bool(props, "bframes", TEXT_BFRAMES);
  725. return props;
  726. }
  727. static void vt_h264_defaults(obs_data_t *settings)
  728. {
  729. obs_data_set_default_int(settings, "bitrate", 2500);
  730. obs_data_set_default_bool(settings, "limit_bitrate", false);
  731. obs_data_set_default_int(settings, "max_bitrate", 2500);
  732. obs_data_set_default_double(settings, "max_bitrate_window", 1.5f);
  733. obs_data_set_default_int(settings, "keyint_sec", 0);
  734. obs_data_set_default_string(settings, "profile", "");
  735. obs_data_set_default_bool(settings, "bframes", true);
  736. }
  737. OBS_DECLARE_MODULE()
  738. OBS_MODULE_USE_DEFAULT_LOCALE("mac-h264", "en-US")
  739. void encoder_list_create()
  740. {
  741. CFArrayRef encoder_list;
  742. VTCopyVideoEncoderList(NULL, &encoder_list);
  743. CFIndex size = CFArrayGetCount(encoder_list);
  744. for (CFIndex i = 0; i < size; i++) {
  745. CFDictionaryRef encoder_dict =
  746. CFArrayGetValueAtIndex(encoder_list, i);
  747. #define VT_DICTSTR(key, name) \
  748. CFStringRef name##_ref = CFDictionaryGetValue(encoder_dict, key); \
  749. CFIndex name##_len = CFStringGetLength(name##_ref); \
  750. char *name = bzalloc(name##_len + 1); \
  751. CFStringGetFileSystemRepresentation(name##_ref, name, name##_len);
  752. VT_DICTSTR(kVTVideoEncoderList_CodecName, codec_name);
  753. if (strcmp("H.264", codec_name) != 0) {
  754. bfree(codec_name);
  755. continue;
  756. }
  757. VT_DICTSTR(kVTVideoEncoderList_EncoderName, name);
  758. VT_DICTSTR(kVTVideoEncoderList_EncoderID, id);
  759. VT_DICTSTR(kVTVideoEncoderList_DisplayName, disp_name);
  760. struct vt_encoder enc = {
  761. .name = name,
  762. .id = id,
  763. .disp_name = disp_name,
  764. .codec_name = codec_name,
  765. };
  766. da_push_back(vt_encoders, &enc);
  767. #undef VT_DICTSTR
  768. }
  769. CFRelease(encoder_list);
  770. }
  771. void encoder_list_destroy()
  772. {
  773. for (size_t i = 0; i < vt_encoders.num; i++) {
  774. bfree((char *)vt_encoders.array[i].name);
  775. bfree((char *)vt_encoders.array[i].id);
  776. bfree((char *)vt_encoders.array[i].codec_name);
  777. bfree((char *)vt_encoders.array[i].disp_name);
  778. }
  779. da_free(vt_encoders);
  780. }
  781. void register_encoders()
  782. {
  783. struct obs_encoder_info info = {
  784. .type = OBS_ENCODER_VIDEO,
  785. .codec = "h264",
  786. .destroy = vt_h264_destroy,
  787. .encode = vt_h264_encode,
  788. .update = vt_h264_update,
  789. .get_properties = vt_h264_properties,
  790. .get_defaults = vt_h264_defaults,
  791. .get_video_info = vt_h264_video_info,
  792. .get_extra_data = vt_h264_extra_data,
  793. .caps = OBS_ENCODER_CAP_DYN_BITRATE,
  794. };
  795. for (size_t i = 0; i < vt_encoders.num; i++) {
  796. info.id = vt_encoders.array[i].id;
  797. info.type_data = (void *)i;
  798. info.get_name = vt_h264_getname;
  799. info.create = vt_h264_create;
  800. obs_register_encoder(&info);
  801. }
  802. }
  803. bool obs_module_load(void)
  804. {
  805. if (!is_appkit10_9_or_greater()) {
  806. VT_LOG(LOG_WARNING, "Not adding VideoToolbox H264 encoder; "
  807. "AppKit must be version 10.9 or greater");
  808. return false;
  809. }
  810. encoder_list_create();
  811. register_encoders();
  812. VT_LOG(LOG_INFO, "Adding VideoToolbox H264 encoders");
  813. return true;
  814. }
  815. void obs_module_unload(void)
  816. {
  817. encoder_list_destroy();
  818. }