encoder.c 27 KB

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