encoder.c 27 KB

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