You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2609 lines
83KB

  1. /*
  2. * copyright (c) 2015 Rick Kern <kernrj@gmail.com>
  3. *
  4. * This file is part of FFmpeg.
  5. *
  6. * FFmpeg is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU Lesser General Public
  8. * License as published by the Free Software Foundation; either
  9. * version 2.1 of the License, or (at your option) any later version.
  10. *
  11. * FFmpeg is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. * Lesser General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Lesser General Public
  17. * License along with FFmpeg; if not, write to the Free Software
  18. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  19. */
  20. #include <VideoToolbox/VideoToolbox.h>
  21. #include <CoreVideo/CoreVideo.h>
  22. #include <CoreMedia/CoreMedia.h>
  23. #include <TargetConditionals.h>
  24. #include <Availability.h>
  25. #include "avcodec.h"
  26. #include "libavutil/opt.h"
  27. #include "libavutil/avassert.h"
  28. #include "libavutil/avstring.h"
  29. #include "libavcodec/avcodec.h"
  30. #include "libavutil/pixdesc.h"
  31. #include "internal.h"
  32. #include <pthread.h>
  33. #include "h264.h"
  34. #include "h264_sei.h"
  35. #include <dlfcn.h>
  36. #if !HAVE_KCMVIDEOCODECTYPE_HEVC
  37. enum { kCMVideoCodecType_HEVC = 'hvc1' };
  38. #endif
  39. typedef OSStatus (*getParameterSetAtIndex)(CMFormatDescriptionRef videoDesc,
  40. size_t parameterSetIndex,
  41. const uint8_t * _Nullable *parameterSetPointerOut,
  42. size_t *parameterSetSizeOut,
  43. size_t *parameterSetCountOut,
  44. int *NALUnitHeaderLengthOut);
  45. //These symbols may not be present
  46. static struct{
  47. CFStringRef kCVImageBufferColorPrimaries_ITU_R_2020;
  48. CFStringRef kCVImageBufferTransferFunction_ITU_R_2020;
  49. CFStringRef kCVImageBufferYCbCrMatrix_ITU_R_2020;
  50. CFStringRef kVTCompressionPropertyKey_H264EntropyMode;
  51. CFStringRef kVTH264EntropyMode_CAVLC;
  52. CFStringRef kVTH264EntropyMode_CABAC;
  53. CFStringRef kVTProfileLevel_H264_Baseline_4_0;
  54. CFStringRef kVTProfileLevel_H264_Baseline_4_2;
  55. CFStringRef kVTProfileLevel_H264_Baseline_5_0;
  56. CFStringRef kVTProfileLevel_H264_Baseline_5_1;
  57. CFStringRef kVTProfileLevel_H264_Baseline_5_2;
  58. CFStringRef kVTProfileLevel_H264_Baseline_AutoLevel;
  59. CFStringRef kVTProfileLevel_H264_Main_4_2;
  60. CFStringRef kVTProfileLevel_H264_Main_5_1;
  61. CFStringRef kVTProfileLevel_H264_Main_5_2;
  62. CFStringRef kVTProfileLevel_H264_Main_AutoLevel;
  63. CFStringRef kVTProfileLevel_H264_High_3_0;
  64. CFStringRef kVTProfileLevel_H264_High_3_1;
  65. CFStringRef kVTProfileLevel_H264_High_3_2;
  66. CFStringRef kVTProfileLevel_H264_High_4_0;
  67. CFStringRef kVTProfileLevel_H264_High_4_1;
  68. CFStringRef kVTProfileLevel_H264_High_4_2;
  69. CFStringRef kVTProfileLevel_H264_High_5_1;
  70. CFStringRef kVTProfileLevel_H264_High_5_2;
  71. CFStringRef kVTProfileLevel_H264_High_AutoLevel;
  72. CFStringRef kVTProfileLevel_HEVC_Main_AutoLevel;
  73. CFStringRef kVTProfileLevel_HEVC_Main10_AutoLevel;
  74. CFStringRef kVTCompressionPropertyKey_RealTime;
  75. CFStringRef kVTVideoEncoderSpecification_EnableHardwareAcceleratedVideoEncoder;
  76. CFStringRef kVTVideoEncoderSpecification_RequireHardwareAcceleratedVideoEncoder;
  77. getParameterSetAtIndex CMVideoFormatDescriptionGetHEVCParameterSetAtIndex;
  78. } compat_keys;
  79. #define GET_SYM(symbol, defaultVal) \
  80. do{ \
  81. CFStringRef* handle = (CFStringRef*)dlsym(RTLD_DEFAULT, #symbol); \
  82. if(!handle) \
  83. compat_keys.symbol = CFSTR(defaultVal); \
  84. else \
  85. compat_keys.symbol = *handle; \
  86. }while(0)
  87. static pthread_once_t once_ctrl = PTHREAD_ONCE_INIT;
  88. static void loadVTEncSymbols(){
  89. compat_keys.CMVideoFormatDescriptionGetHEVCParameterSetAtIndex =
  90. (getParameterSetAtIndex)dlsym(
  91. RTLD_DEFAULT,
  92. "CMVideoFormatDescriptionGetHEVCParameterSetAtIndex"
  93. );
  94. GET_SYM(kCVImageBufferColorPrimaries_ITU_R_2020, "ITU_R_2020");
  95. GET_SYM(kCVImageBufferTransferFunction_ITU_R_2020, "ITU_R_2020");
  96. GET_SYM(kCVImageBufferYCbCrMatrix_ITU_R_2020, "ITU_R_2020");
  97. GET_SYM(kVTCompressionPropertyKey_H264EntropyMode, "H264EntropyMode");
  98. GET_SYM(kVTH264EntropyMode_CAVLC, "CAVLC");
  99. GET_SYM(kVTH264EntropyMode_CABAC, "CABAC");
  100. GET_SYM(kVTProfileLevel_H264_Baseline_4_0, "H264_Baseline_4_0");
  101. GET_SYM(kVTProfileLevel_H264_Baseline_4_2, "H264_Baseline_4_2");
  102. GET_SYM(kVTProfileLevel_H264_Baseline_5_0, "H264_Baseline_5_0");
  103. GET_SYM(kVTProfileLevel_H264_Baseline_5_1, "H264_Baseline_5_1");
  104. GET_SYM(kVTProfileLevel_H264_Baseline_5_2, "H264_Baseline_5_2");
  105. GET_SYM(kVTProfileLevel_H264_Baseline_AutoLevel, "H264_Baseline_AutoLevel");
  106. GET_SYM(kVTProfileLevel_H264_Main_4_2, "H264_Main_4_2");
  107. GET_SYM(kVTProfileLevel_H264_Main_5_1, "H264_Main_5_1");
  108. GET_SYM(kVTProfileLevel_H264_Main_5_2, "H264_Main_5_2");
  109. GET_SYM(kVTProfileLevel_H264_Main_AutoLevel, "H264_Main_AutoLevel");
  110. GET_SYM(kVTProfileLevel_H264_High_3_0, "H264_High_3_0");
  111. GET_SYM(kVTProfileLevel_H264_High_3_1, "H264_High_3_1");
  112. GET_SYM(kVTProfileLevel_H264_High_3_2, "H264_High_3_2");
  113. GET_SYM(kVTProfileLevel_H264_High_4_0, "H264_High_4_0");
  114. GET_SYM(kVTProfileLevel_H264_High_4_1, "H264_High_4_1");
  115. GET_SYM(kVTProfileLevel_H264_High_4_2, "H264_High_4_2");
  116. GET_SYM(kVTProfileLevel_H264_High_5_1, "H264_High_5_1");
  117. GET_SYM(kVTProfileLevel_H264_High_5_2, "H264_High_5_2");
  118. GET_SYM(kVTProfileLevel_H264_High_AutoLevel, "H264_High_AutoLevel");
  119. GET_SYM(kVTProfileLevel_HEVC_Main_AutoLevel, "HEVC_Main_AutoLevel");
  120. GET_SYM(kVTProfileLevel_HEVC_Main10_AutoLevel, "HEVC_Main10_AutoLevel");
  121. GET_SYM(kVTCompressionPropertyKey_RealTime, "RealTime");
  122. GET_SYM(kVTVideoEncoderSpecification_EnableHardwareAcceleratedVideoEncoder,
  123. "EnableHardwareAcceleratedVideoEncoder");
  124. GET_SYM(kVTVideoEncoderSpecification_RequireHardwareAcceleratedVideoEncoder,
  125. "RequireHardwareAcceleratedVideoEncoder");
  126. }
  127. typedef enum VT_H264Profile {
  128. H264_PROF_AUTO,
  129. H264_PROF_BASELINE,
  130. H264_PROF_MAIN,
  131. H264_PROF_HIGH,
  132. H264_PROF_COUNT
  133. } VT_H264Profile;
  134. typedef enum VTH264Entropy{
  135. VT_ENTROPY_NOT_SET,
  136. VT_CAVLC,
  137. VT_CABAC
  138. } VTH264Entropy;
  139. typedef enum VT_HEVCProfile {
  140. HEVC_PROF_AUTO,
  141. HEVC_PROF_MAIN,
  142. HEVC_PROF_MAIN10,
  143. HEVC_PROF_COUNT
  144. } VT_HEVCProfile;
  145. static const uint8_t start_code[] = { 0, 0, 0, 1 };
  146. typedef struct ExtraSEI {
  147. void *data;
  148. size_t size;
  149. } ExtraSEI;
  150. typedef struct BufNode {
  151. CMSampleBufferRef cm_buffer;
  152. ExtraSEI *sei;
  153. struct BufNode* next;
  154. int error;
  155. } BufNode;
  156. typedef struct VTEncContext {
  157. AVClass *class;
  158. enum AVCodecID codec_id;
  159. VTCompressionSessionRef session;
  160. CFStringRef ycbcr_matrix;
  161. CFStringRef color_primaries;
  162. CFStringRef transfer_function;
  163. getParameterSetAtIndex get_param_set_func;
  164. pthread_mutex_t lock;
  165. pthread_cond_t cv_sample_sent;
  166. int async_error;
  167. BufNode *q_head;
  168. BufNode *q_tail;
  169. int64_t frame_ct_out;
  170. int64_t frame_ct_in;
  171. int64_t first_pts;
  172. int64_t dts_delta;
  173. int64_t profile;
  174. int64_t level;
  175. int64_t entropy;
  176. int64_t realtime;
  177. int64_t frames_before;
  178. int64_t frames_after;
  179. int64_t allow_sw;
  180. bool flushing;
  181. bool has_b_frames;
  182. bool warned_color_range;
  183. bool a53_cc;
  184. } VTEncContext;
  185. static int vtenc_populate_extradata(AVCodecContext *avctx,
  186. CMVideoCodecType codec_type,
  187. CFStringRef profile_level,
  188. CFNumberRef gamma_level,
  189. CFDictionaryRef enc_info,
  190. CFDictionaryRef pixel_buffer_info);
  191. /**
  192. * NULL-safe release of *refPtr, and sets value to NULL.
  193. */
  194. static void vt_release_num(CFNumberRef* refPtr){
  195. if (!*refPtr) {
  196. return;
  197. }
  198. CFRelease(*refPtr);
  199. *refPtr = NULL;
  200. }
  201. static void set_async_error(VTEncContext *vtctx, int err)
  202. {
  203. BufNode *info;
  204. pthread_mutex_lock(&vtctx->lock);
  205. vtctx->async_error = err;
  206. info = vtctx->q_head;
  207. vtctx->q_head = vtctx->q_tail = NULL;
  208. while (info) {
  209. BufNode *next = info->next;
  210. CFRelease(info->cm_buffer);
  211. av_free(info);
  212. info = next;
  213. }
  214. pthread_mutex_unlock(&vtctx->lock);
  215. }
  216. static void clear_frame_queue(VTEncContext *vtctx)
  217. {
  218. set_async_error(vtctx, 0);
  219. }
  220. static int vtenc_q_pop(VTEncContext *vtctx, bool wait, CMSampleBufferRef *buf, ExtraSEI **sei)
  221. {
  222. BufNode *info;
  223. pthread_mutex_lock(&vtctx->lock);
  224. if (vtctx->async_error) {
  225. pthread_mutex_unlock(&vtctx->lock);
  226. return vtctx->async_error;
  227. }
  228. if (vtctx->flushing && vtctx->frame_ct_in == vtctx->frame_ct_out) {
  229. *buf = NULL;
  230. pthread_mutex_unlock(&vtctx->lock);
  231. return 0;
  232. }
  233. while (!vtctx->q_head && !vtctx->async_error && wait) {
  234. pthread_cond_wait(&vtctx->cv_sample_sent, &vtctx->lock);
  235. }
  236. if (!vtctx->q_head) {
  237. pthread_mutex_unlock(&vtctx->lock);
  238. *buf = NULL;
  239. return 0;
  240. }
  241. info = vtctx->q_head;
  242. vtctx->q_head = vtctx->q_head->next;
  243. if (!vtctx->q_head) {
  244. vtctx->q_tail = NULL;
  245. }
  246. pthread_mutex_unlock(&vtctx->lock);
  247. *buf = info->cm_buffer;
  248. if (sei && *buf) {
  249. *sei = info->sei;
  250. } else if (info->sei) {
  251. if (info->sei->data) av_free(info->sei->data);
  252. av_free(info->sei);
  253. }
  254. av_free(info);
  255. vtctx->frame_ct_out++;
  256. return 0;
  257. }
  258. static void vtenc_q_push(VTEncContext *vtctx, CMSampleBufferRef buffer, ExtraSEI *sei)
  259. {
  260. BufNode *info = av_malloc(sizeof(BufNode));
  261. if (!info) {
  262. set_async_error(vtctx, AVERROR(ENOMEM));
  263. return;
  264. }
  265. CFRetain(buffer);
  266. info->cm_buffer = buffer;
  267. info->sei = sei;
  268. info->next = NULL;
  269. pthread_mutex_lock(&vtctx->lock);
  270. pthread_cond_signal(&vtctx->cv_sample_sent);
  271. if (!vtctx->q_head) {
  272. vtctx->q_head = info;
  273. } else {
  274. vtctx->q_tail->next = info;
  275. }
  276. vtctx->q_tail = info;
  277. pthread_mutex_unlock(&vtctx->lock);
  278. }
  279. static int count_nalus(size_t length_code_size,
  280. CMSampleBufferRef sample_buffer,
  281. int *count)
  282. {
  283. size_t offset = 0;
  284. int status;
  285. int nalu_ct = 0;
  286. uint8_t size_buf[4];
  287. size_t src_size = CMSampleBufferGetTotalSampleSize(sample_buffer);
  288. CMBlockBufferRef block = CMSampleBufferGetDataBuffer(sample_buffer);
  289. if (length_code_size > 4)
  290. return AVERROR_INVALIDDATA;
  291. while (offset < src_size) {
  292. size_t curr_src_len;
  293. size_t box_len = 0;
  294. size_t i;
  295. status = CMBlockBufferCopyDataBytes(block,
  296. offset,
  297. length_code_size,
  298. size_buf);
  299. for (i = 0; i < length_code_size; i++) {
  300. box_len <<= 8;
  301. box_len |= size_buf[i];
  302. }
  303. curr_src_len = box_len + length_code_size;
  304. offset += curr_src_len;
  305. nalu_ct++;
  306. }
  307. *count = nalu_ct;
  308. return 0;
  309. }
  310. static CMVideoCodecType get_cm_codec_type(enum AVCodecID id)
  311. {
  312. switch (id) {
  313. case AV_CODEC_ID_H264: return kCMVideoCodecType_H264;
  314. case AV_CODEC_ID_HEVC: return kCMVideoCodecType_HEVC;
  315. default: return 0;
  316. }
  317. }
  318. /**
  319. * Get the parameter sets from a CMSampleBufferRef.
  320. * @param dst If *dst isn't NULL, the parameters are copied into existing
  321. * memory. *dst_size must be set accordingly when *dst != NULL.
  322. * If *dst is NULL, it will be allocated.
  323. * In all cases, *dst_size is set to the number of bytes used starting
  324. * at *dst.
  325. */
  326. static int get_params_size(
  327. AVCodecContext *avctx,
  328. CMVideoFormatDescriptionRef vid_fmt,
  329. size_t *size)
  330. {
  331. VTEncContext *vtctx = avctx->priv_data;
  332. size_t total_size = 0;
  333. size_t ps_count;
  334. int is_count_bad = 0;
  335. size_t i;
  336. int status;
  337. status = vtctx->get_param_set_func(vid_fmt,
  338. 0,
  339. NULL,
  340. NULL,
  341. &ps_count,
  342. NULL);
  343. if (status) {
  344. is_count_bad = 1;
  345. ps_count = 0;
  346. status = 0;
  347. }
  348. for (i = 0; i < ps_count || is_count_bad; i++) {
  349. const uint8_t *ps;
  350. size_t ps_size;
  351. status = vtctx->get_param_set_func(vid_fmt,
  352. i,
  353. &ps,
  354. &ps_size,
  355. NULL,
  356. NULL);
  357. if (status) {
  358. /*
  359. * When ps_count is invalid, status != 0 ends the loop normally
  360. * unless we didn't get any parameter sets.
  361. */
  362. if (i > 0 && is_count_bad) status = 0;
  363. break;
  364. }
  365. total_size += ps_size + sizeof(start_code);
  366. }
  367. if (status) {
  368. av_log(avctx, AV_LOG_ERROR, "Error getting parameter set sizes: %d\n", status);
  369. return AVERROR_EXTERNAL;
  370. }
  371. *size = total_size;
  372. return 0;
  373. }
  374. static int copy_param_sets(
  375. AVCodecContext *avctx,
  376. CMVideoFormatDescriptionRef vid_fmt,
  377. uint8_t *dst,
  378. size_t dst_size)
  379. {
  380. VTEncContext *vtctx = avctx->priv_data;
  381. size_t ps_count;
  382. int is_count_bad = 0;
  383. int status;
  384. size_t offset = 0;
  385. size_t i;
  386. status = vtctx->get_param_set_func(vid_fmt,
  387. 0,
  388. NULL,
  389. NULL,
  390. &ps_count,
  391. NULL);
  392. if (status) {
  393. is_count_bad = 1;
  394. ps_count = 0;
  395. status = 0;
  396. }
  397. for (i = 0; i < ps_count || is_count_bad; i++) {
  398. const uint8_t *ps;
  399. size_t ps_size;
  400. size_t next_offset;
  401. status = vtctx->get_param_set_func(vid_fmt,
  402. i,
  403. &ps,
  404. &ps_size,
  405. NULL,
  406. NULL);
  407. if (status) {
  408. if (i > 0 && is_count_bad) status = 0;
  409. break;
  410. }
  411. next_offset = offset + sizeof(start_code) + ps_size;
  412. if (dst_size < next_offset) {
  413. av_log(avctx, AV_LOG_ERROR, "Error: buffer too small for parameter sets.\n");
  414. return AVERROR_BUFFER_TOO_SMALL;
  415. }
  416. memcpy(dst + offset, start_code, sizeof(start_code));
  417. offset += sizeof(start_code);
  418. memcpy(dst + offset, ps, ps_size);
  419. offset = next_offset;
  420. }
  421. if (status) {
  422. av_log(avctx, AV_LOG_ERROR, "Error getting parameter set data: %d\n", status);
  423. return AVERROR_EXTERNAL;
  424. }
  425. return 0;
  426. }
  427. static int set_extradata(AVCodecContext *avctx, CMSampleBufferRef sample_buffer)
  428. {
  429. CMVideoFormatDescriptionRef vid_fmt;
  430. size_t total_size;
  431. int status;
  432. vid_fmt = CMSampleBufferGetFormatDescription(sample_buffer);
  433. if (!vid_fmt) {
  434. av_log(avctx, AV_LOG_ERROR, "No video format.\n");
  435. return AVERROR_EXTERNAL;
  436. }
  437. status = get_params_size(avctx, vid_fmt, &total_size);
  438. if (status) {
  439. av_log(avctx, AV_LOG_ERROR, "Could not get parameter sets.\n");
  440. return status;
  441. }
  442. avctx->extradata = av_mallocz(total_size + AV_INPUT_BUFFER_PADDING_SIZE);
  443. if (!avctx->extradata) {
  444. return AVERROR(ENOMEM);
  445. }
  446. avctx->extradata_size = total_size;
  447. status = copy_param_sets(avctx, vid_fmt, avctx->extradata, total_size);
  448. if (status) {
  449. av_log(avctx, AV_LOG_ERROR, "Could not copy param sets.\n");
  450. return status;
  451. }
  452. return 0;
  453. }
  454. static void vtenc_output_callback(
  455. void *ctx,
  456. void *sourceFrameCtx,
  457. OSStatus status,
  458. VTEncodeInfoFlags flags,
  459. CMSampleBufferRef sample_buffer)
  460. {
  461. AVCodecContext *avctx = ctx;
  462. VTEncContext *vtctx = avctx->priv_data;
  463. ExtraSEI *sei = sourceFrameCtx;
  464. if (vtctx->async_error) {
  465. if(sample_buffer) CFRelease(sample_buffer);
  466. return;
  467. }
  468. if (status || !sample_buffer) {
  469. av_log(avctx, AV_LOG_ERROR, "Error encoding frame: %d\n", (int)status);
  470. set_async_error(vtctx, AVERROR_EXTERNAL);
  471. return;
  472. }
  473. if (!avctx->extradata && (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER)) {
  474. int set_status = set_extradata(avctx, sample_buffer);
  475. if (set_status) {
  476. set_async_error(vtctx, set_status);
  477. return;
  478. }
  479. }
  480. vtenc_q_push(vtctx, sample_buffer, sei);
  481. }
  482. static int get_length_code_size(
  483. AVCodecContext *avctx,
  484. CMSampleBufferRef sample_buffer,
  485. size_t *size)
  486. {
  487. VTEncContext *vtctx = avctx->priv_data;
  488. CMVideoFormatDescriptionRef vid_fmt;
  489. int isize;
  490. int status;
  491. vid_fmt = CMSampleBufferGetFormatDescription(sample_buffer);
  492. if (!vid_fmt) {
  493. av_log(avctx, AV_LOG_ERROR, "Error getting buffer format description.\n");
  494. return AVERROR_EXTERNAL;
  495. }
  496. status = vtctx->get_param_set_func(vid_fmt,
  497. 0,
  498. NULL,
  499. NULL,
  500. NULL,
  501. &isize);
  502. if (status) {
  503. av_log(avctx, AV_LOG_ERROR, "Error getting length code size: %d\n", status);
  504. return AVERROR_EXTERNAL;
  505. }
  506. *size = isize;
  507. return 0;
  508. }
  509. /*
  510. * Returns true on success.
  511. *
  512. * If profile_level_val is NULL and this method returns true, don't specify the
  513. * profile/level to the encoder.
  514. */
  515. static bool get_vt_h264_profile_level(AVCodecContext *avctx,
  516. CFStringRef *profile_level_val)
  517. {
  518. VTEncContext *vtctx = avctx->priv_data;
  519. int64_t profile = vtctx->profile;
  520. if (profile == H264_PROF_AUTO && vtctx->level) {
  521. //Need to pick a profile if level is not auto-selected.
  522. profile = vtctx->has_b_frames ? H264_PROF_MAIN : H264_PROF_BASELINE;
  523. }
  524. *profile_level_val = NULL;
  525. switch (profile) {
  526. case H264_PROF_AUTO:
  527. return true;
  528. case H264_PROF_BASELINE:
  529. switch (vtctx->level) {
  530. case 0: *profile_level_val =
  531. compat_keys.kVTProfileLevel_H264_Baseline_AutoLevel; break;
  532. case 13: *profile_level_val = kVTProfileLevel_H264_Baseline_1_3; break;
  533. case 30: *profile_level_val = kVTProfileLevel_H264_Baseline_3_0; break;
  534. case 31: *profile_level_val = kVTProfileLevel_H264_Baseline_3_1; break;
  535. case 32: *profile_level_val = kVTProfileLevel_H264_Baseline_3_2; break;
  536. case 40: *profile_level_val =
  537. compat_keys.kVTProfileLevel_H264_Baseline_4_0; break;
  538. case 41: *profile_level_val = kVTProfileLevel_H264_Baseline_4_1; break;
  539. case 42: *profile_level_val =
  540. compat_keys.kVTProfileLevel_H264_Baseline_4_2; break;
  541. case 50: *profile_level_val =
  542. compat_keys.kVTProfileLevel_H264_Baseline_5_0; break;
  543. case 51: *profile_level_val =
  544. compat_keys.kVTProfileLevel_H264_Baseline_5_1; break;
  545. case 52: *profile_level_val =
  546. compat_keys.kVTProfileLevel_H264_Baseline_5_2; break;
  547. }
  548. break;
  549. case H264_PROF_MAIN:
  550. switch (vtctx->level) {
  551. case 0: *profile_level_val =
  552. compat_keys.kVTProfileLevel_H264_Main_AutoLevel; break;
  553. case 30: *profile_level_val = kVTProfileLevel_H264_Main_3_0; break;
  554. case 31: *profile_level_val = kVTProfileLevel_H264_Main_3_1; break;
  555. case 32: *profile_level_val = kVTProfileLevel_H264_Main_3_2; break;
  556. case 40: *profile_level_val = kVTProfileLevel_H264_Main_4_0; break;
  557. case 41: *profile_level_val = kVTProfileLevel_H264_Main_4_1; break;
  558. case 42: *profile_level_val =
  559. compat_keys.kVTProfileLevel_H264_Main_4_2; break;
  560. case 50: *profile_level_val = kVTProfileLevel_H264_Main_5_0; break;
  561. case 51: *profile_level_val =
  562. compat_keys.kVTProfileLevel_H264_Main_5_1; break;
  563. case 52: *profile_level_val =
  564. compat_keys.kVTProfileLevel_H264_Main_5_2; break;
  565. }
  566. break;
  567. case H264_PROF_HIGH:
  568. switch (vtctx->level) {
  569. case 0: *profile_level_val =
  570. compat_keys.kVTProfileLevel_H264_High_AutoLevel; break;
  571. case 30: *profile_level_val =
  572. compat_keys.kVTProfileLevel_H264_High_3_0; break;
  573. case 31: *profile_level_val =
  574. compat_keys.kVTProfileLevel_H264_High_3_1; break;
  575. case 32: *profile_level_val =
  576. compat_keys.kVTProfileLevel_H264_High_3_2; break;
  577. case 40: *profile_level_val =
  578. compat_keys.kVTProfileLevel_H264_High_4_0; break;
  579. case 41: *profile_level_val =
  580. compat_keys.kVTProfileLevel_H264_High_4_1; break;
  581. case 42: *profile_level_val =
  582. compat_keys.kVTProfileLevel_H264_High_4_2; break;
  583. case 50: *profile_level_val = kVTProfileLevel_H264_High_5_0; break;
  584. case 51: *profile_level_val =
  585. compat_keys.kVTProfileLevel_H264_High_5_1; break;
  586. case 52: *profile_level_val =
  587. compat_keys.kVTProfileLevel_H264_High_5_2; break;
  588. }
  589. break;
  590. }
  591. if (!*profile_level_val) {
  592. av_log(avctx, AV_LOG_ERROR, "Invalid Profile/Level.\n");
  593. return false;
  594. }
  595. return true;
  596. }
  597. /*
  598. * Returns true on success.
  599. *
  600. * If profile_level_val is NULL and this method returns true, don't specify the
  601. * profile/level to the encoder.
  602. */
  603. static bool get_vt_hevc_profile_level(AVCodecContext *avctx,
  604. CFStringRef *profile_level_val)
  605. {
  606. VTEncContext *vtctx = avctx->priv_data;
  607. int64_t profile = vtctx->profile;
  608. *profile_level_val = NULL;
  609. switch (profile) {
  610. case HEVC_PROF_AUTO:
  611. return true;
  612. case HEVC_PROF_MAIN:
  613. *profile_level_val =
  614. compat_keys.kVTProfileLevel_HEVC_Main_AutoLevel;
  615. break;
  616. case HEVC_PROF_MAIN10:
  617. *profile_level_val =
  618. compat_keys.kVTProfileLevel_HEVC_Main10_AutoLevel;
  619. break;
  620. }
  621. if (!*profile_level_val) {
  622. av_log(avctx, AV_LOG_ERROR, "Invalid Profile/Level.\n");
  623. return false;
  624. }
  625. return true;
  626. }
  627. static int get_cv_pixel_format(AVCodecContext* avctx,
  628. enum AVPixelFormat fmt,
  629. enum AVColorRange range,
  630. int* av_pixel_format,
  631. int* range_guessed)
  632. {
  633. if (range_guessed) *range_guessed = range != AVCOL_RANGE_MPEG &&
  634. range != AVCOL_RANGE_JPEG;
  635. //MPEG range is used when no range is set
  636. if (fmt == AV_PIX_FMT_NV12) {
  637. *av_pixel_format = range == AVCOL_RANGE_JPEG ?
  638. kCVPixelFormatType_420YpCbCr8BiPlanarFullRange :
  639. kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange;
  640. } else if (fmt == AV_PIX_FMT_YUV420P) {
  641. *av_pixel_format = range == AVCOL_RANGE_JPEG ?
  642. kCVPixelFormatType_420YpCbCr8PlanarFullRange :
  643. kCVPixelFormatType_420YpCbCr8Planar;
  644. } else {
  645. return AVERROR(EINVAL);
  646. }
  647. return 0;
  648. }
  649. static void add_color_attr(AVCodecContext *avctx, CFMutableDictionaryRef dict) {
  650. VTEncContext *vtctx = avctx->priv_data;
  651. if (vtctx->color_primaries) {
  652. CFDictionarySetValue(dict,
  653. kCVImageBufferColorPrimariesKey,
  654. vtctx->color_primaries);
  655. }
  656. if (vtctx->transfer_function) {
  657. CFDictionarySetValue(dict,
  658. kCVImageBufferTransferFunctionKey,
  659. vtctx->transfer_function);
  660. }
  661. if (vtctx->ycbcr_matrix) {
  662. CFDictionarySetValue(dict,
  663. kCVImageBufferYCbCrMatrixKey,
  664. vtctx->ycbcr_matrix);
  665. }
  666. }
  667. static int create_cv_pixel_buffer_info(AVCodecContext* avctx,
  668. CFMutableDictionaryRef* dict)
  669. {
  670. CFNumberRef cv_color_format_num = NULL;
  671. CFNumberRef width_num = NULL;
  672. CFNumberRef height_num = NULL;
  673. CFMutableDictionaryRef pixel_buffer_info = NULL;
  674. int cv_color_format;
  675. int status = get_cv_pixel_format(avctx,
  676. avctx->pix_fmt,
  677. avctx->color_range,
  678. &cv_color_format,
  679. NULL);
  680. if (status) return status;
  681. pixel_buffer_info = CFDictionaryCreateMutable(
  682. kCFAllocatorDefault,
  683. 20,
  684. &kCFCopyStringDictionaryKeyCallBacks,
  685. &kCFTypeDictionaryValueCallBacks);
  686. if (!pixel_buffer_info) goto pbinfo_nomem;
  687. cv_color_format_num = CFNumberCreate(kCFAllocatorDefault,
  688. kCFNumberSInt32Type,
  689. &cv_color_format);
  690. if (!cv_color_format_num) goto pbinfo_nomem;
  691. CFDictionarySetValue(pixel_buffer_info,
  692. kCVPixelBufferPixelFormatTypeKey,
  693. cv_color_format_num);
  694. vt_release_num(&cv_color_format_num);
  695. width_num = CFNumberCreate(kCFAllocatorDefault,
  696. kCFNumberSInt32Type,
  697. &avctx->width);
  698. if (!width_num) return AVERROR(ENOMEM);
  699. CFDictionarySetValue(pixel_buffer_info,
  700. kCVPixelBufferWidthKey,
  701. width_num);
  702. vt_release_num(&width_num);
  703. height_num = CFNumberCreate(kCFAllocatorDefault,
  704. kCFNumberSInt32Type,
  705. &avctx->height);
  706. if (!height_num) goto pbinfo_nomem;
  707. CFDictionarySetValue(pixel_buffer_info,
  708. kCVPixelBufferHeightKey,
  709. height_num);
  710. vt_release_num(&height_num);
  711. add_color_attr(avctx, pixel_buffer_info);
  712. *dict = pixel_buffer_info;
  713. return 0;
  714. pbinfo_nomem:
  715. vt_release_num(&cv_color_format_num);
  716. vt_release_num(&width_num);
  717. vt_release_num(&height_num);
  718. if (pixel_buffer_info) CFRelease(pixel_buffer_info);
  719. return AVERROR(ENOMEM);
  720. }
  721. static int get_cv_color_primaries(AVCodecContext *avctx,
  722. CFStringRef *primaries)
  723. {
  724. enum AVColorPrimaries pri = avctx->color_primaries;
  725. switch (pri) {
  726. case AVCOL_PRI_UNSPECIFIED:
  727. *primaries = NULL;
  728. break;
  729. case AVCOL_PRI_BT709:
  730. *primaries = kCVImageBufferColorPrimaries_ITU_R_709_2;
  731. break;
  732. case AVCOL_PRI_BT2020:
  733. *primaries = compat_keys.kCVImageBufferColorPrimaries_ITU_R_2020;
  734. break;
  735. default:
  736. av_log(avctx, AV_LOG_ERROR, "Color primaries %s is not supported.\n", av_color_primaries_name(pri));
  737. *primaries = NULL;
  738. return -1;
  739. }
  740. return 0;
  741. }
  742. static int get_cv_transfer_function(AVCodecContext *avctx,
  743. CFStringRef *transfer_fnc,
  744. CFNumberRef *gamma_level)
  745. {
  746. enum AVColorTransferCharacteristic trc = avctx->color_trc;
  747. Float32 gamma;
  748. *gamma_level = NULL;
  749. switch (trc) {
  750. case AVCOL_TRC_UNSPECIFIED:
  751. *transfer_fnc = NULL;
  752. break;
  753. case AVCOL_TRC_BT709:
  754. *transfer_fnc = kCVImageBufferTransferFunction_ITU_R_709_2;
  755. break;
  756. case AVCOL_TRC_SMPTE240M:
  757. *transfer_fnc = kCVImageBufferTransferFunction_SMPTE_240M_1995;
  758. break;
  759. case AVCOL_TRC_GAMMA22:
  760. gamma = 2.2;
  761. *transfer_fnc = kCVImageBufferTransferFunction_UseGamma;
  762. *gamma_level = CFNumberCreate(NULL, kCFNumberFloat32Type, &gamma);
  763. break;
  764. case AVCOL_TRC_GAMMA28:
  765. gamma = 2.8;
  766. *transfer_fnc = kCVImageBufferTransferFunction_UseGamma;
  767. *gamma_level = CFNumberCreate(NULL, kCFNumberFloat32Type, &gamma);
  768. break;
  769. case AVCOL_TRC_BT2020_10:
  770. case AVCOL_TRC_BT2020_12:
  771. *transfer_fnc = compat_keys.kCVImageBufferTransferFunction_ITU_R_2020;
  772. break;
  773. default:
  774. av_log(avctx, AV_LOG_ERROR, "Transfer function %s is not supported.\n", av_color_transfer_name(trc));
  775. return -1;
  776. }
  777. return 0;
  778. }
  779. static int get_cv_ycbcr_matrix(AVCodecContext *avctx, CFStringRef *matrix) {
  780. switch(avctx->colorspace) {
  781. case AVCOL_SPC_BT709:
  782. *matrix = kCVImageBufferYCbCrMatrix_ITU_R_709_2;
  783. break;
  784. case AVCOL_SPC_UNSPECIFIED:
  785. *matrix = NULL;
  786. break;
  787. case AVCOL_SPC_BT470BG:
  788. case AVCOL_SPC_SMPTE170M:
  789. *matrix = kCVImageBufferYCbCrMatrix_ITU_R_601_4;
  790. break;
  791. case AVCOL_SPC_SMPTE240M:
  792. *matrix = kCVImageBufferYCbCrMatrix_SMPTE_240M_1995;
  793. break;
  794. case AVCOL_SPC_BT2020_NCL:
  795. *matrix = compat_keys.kCVImageBufferYCbCrMatrix_ITU_R_2020;
  796. break;
  797. default:
  798. av_log(avctx, AV_LOG_ERROR, "Color space %s is not supported.\n", av_color_space_name(avctx->colorspace));
  799. return -1;
  800. }
  801. return 0;
  802. }
  803. static int vtenc_create_encoder(AVCodecContext *avctx,
  804. CMVideoCodecType codec_type,
  805. CFStringRef profile_level,
  806. CFNumberRef gamma_level,
  807. CFDictionaryRef enc_info,
  808. CFDictionaryRef pixel_buffer_info,
  809. VTCompressionSessionRef *session)
  810. {
  811. VTEncContext *vtctx = avctx->priv_data;
  812. SInt32 bit_rate = avctx->bit_rate;
  813. SInt32 max_rate = avctx->rc_max_rate;
  814. CFNumberRef bit_rate_num;
  815. CFNumberRef bytes_per_second;
  816. CFNumberRef one_second;
  817. CFArrayRef data_rate_limits;
  818. int64_t bytes_per_second_value = 0;
  819. int64_t one_second_value = 0;
  820. void *nums[2];
  821. int status = VTCompressionSessionCreate(kCFAllocatorDefault,
  822. avctx->width,
  823. avctx->height,
  824. codec_type,
  825. enc_info,
  826. pixel_buffer_info,
  827. kCFAllocatorDefault,
  828. vtenc_output_callback,
  829. avctx,
  830. session);
  831. if (status || !vtctx->session) {
  832. av_log(avctx, AV_LOG_ERROR, "Error: cannot create compression session: %d\n", status);
  833. #if !TARGET_OS_IPHONE
  834. if (!vtctx->allow_sw) {
  835. av_log(avctx, AV_LOG_ERROR, "Try -allow_sw 1. The hardware encoder may be busy, or not supported.\n");
  836. }
  837. #endif
  838. return AVERROR_EXTERNAL;
  839. }
  840. bit_rate_num = CFNumberCreate(kCFAllocatorDefault,
  841. kCFNumberSInt32Type,
  842. &bit_rate);
  843. if (!bit_rate_num) return AVERROR(ENOMEM);
  844. status = VTSessionSetProperty(vtctx->session,
  845. kVTCompressionPropertyKey_AverageBitRate,
  846. bit_rate_num);
  847. CFRelease(bit_rate_num);
  848. if (status) {
  849. av_log(avctx, AV_LOG_ERROR, "Error setting bitrate property: %d\n", status);
  850. return AVERROR_EXTERNAL;
  851. }
  852. if (vtctx->codec_id == AV_CODEC_ID_H264) {
  853. // kVTCompressionPropertyKey_DataRateLimits is not available for HEVC
  854. bytes_per_second_value = max_rate >> 3;
  855. bytes_per_second = CFNumberCreate(kCFAllocatorDefault,
  856. kCFNumberSInt64Type,
  857. &bytes_per_second_value);
  858. if (!bytes_per_second) {
  859. return AVERROR(ENOMEM);
  860. }
  861. one_second_value = 1;
  862. one_second = CFNumberCreate(kCFAllocatorDefault,
  863. kCFNumberSInt64Type,
  864. &one_second_value);
  865. if (!one_second) {
  866. CFRelease(bytes_per_second);
  867. return AVERROR(ENOMEM);
  868. }
  869. nums[0] = (void *)bytes_per_second;
  870. nums[1] = (void *)one_second;
  871. data_rate_limits = CFArrayCreate(kCFAllocatorDefault,
  872. (const void **)nums,
  873. 2,
  874. &kCFTypeArrayCallBacks);
  875. if (!data_rate_limits) {
  876. CFRelease(bytes_per_second);
  877. CFRelease(one_second);
  878. return AVERROR(ENOMEM);
  879. }
  880. status = VTSessionSetProperty(vtctx->session,
  881. kVTCompressionPropertyKey_DataRateLimits,
  882. data_rate_limits);
  883. CFRelease(bytes_per_second);
  884. CFRelease(one_second);
  885. CFRelease(data_rate_limits);
  886. if (status) {
  887. av_log(avctx, AV_LOG_ERROR, "Error setting max bitrate property: %d\n", status);
  888. return AVERROR_EXTERNAL;
  889. }
  890. if (profile_level) {
  891. status = VTSessionSetProperty(vtctx->session,
  892. kVTCompressionPropertyKey_ProfileLevel,
  893. profile_level);
  894. if (status) {
  895. av_log(avctx, AV_LOG_ERROR, "Error setting profile/level property: %d\n", status);
  896. }
  897. }
  898. }
  899. if (avctx->gop_size > 0) {
  900. CFNumberRef interval = CFNumberCreate(kCFAllocatorDefault,
  901. kCFNumberIntType,
  902. &avctx->gop_size);
  903. if (!interval) {
  904. return AVERROR(ENOMEM);
  905. }
  906. status = VTSessionSetProperty(vtctx->session,
  907. kVTCompressionPropertyKey_MaxKeyFrameInterval,
  908. interval);
  909. CFRelease(interval);
  910. if (status) {
  911. av_log(avctx, AV_LOG_ERROR, "Error setting 'max key-frame interval' property: %d\n", status);
  912. return AVERROR_EXTERNAL;
  913. }
  914. }
  915. if (vtctx->frames_before) {
  916. status = VTSessionSetProperty(vtctx->session,
  917. kVTCompressionPropertyKey_MoreFramesBeforeStart,
  918. kCFBooleanTrue);
  919. if (status == kVTPropertyNotSupportedErr) {
  920. av_log(avctx, AV_LOG_WARNING, "frames_before property is not supported on this device. Ignoring.\n");
  921. } else if (status) {
  922. av_log(avctx, AV_LOG_ERROR, "Error setting frames_before property: %d\n", status);
  923. }
  924. }
  925. if (vtctx->frames_after) {
  926. status = VTSessionSetProperty(vtctx->session,
  927. kVTCompressionPropertyKey_MoreFramesAfterEnd,
  928. kCFBooleanTrue);
  929. if (status == kVTPropertyNotSupportedErr) {
  930. av_log(avctx, AV_LOG_WARNING, "frames_after property is not supported on this device. Ignoring.\n");
  931. } else if (status) {
  932. av_log(avctx, AV_LOG_ERROR, "Error setting frames_after property: %d\n", status);
  933. }
  934. }
  935. if (avctx->sample_aspect_ratio.num != 0) {
  936. CFNumberRef num;
  937. CFNumberRef den;
  938. CFMutableDictionaryRef par;
  939. AVRational *avpar = &avctx->sample_aspect_ratio;
  940. av_reduce(&avpar->num, &avpar->den,
  941. avpar->num, avpar->den,
  942. 0xFFFFFFFF);
  943. num = CFNumberCreate(kCFAllocatorDefault,
  944. kCFNumberIntType,
  945. &avpar->num);
  946. den = CFNumberCreate(kCFAllocatorDefault,
  947. kCFNumberIntType,
  948. &avpar->den);
  949. par = CFDictionaryCreateMutable(kCFAllocatorDefault,
  950. 2,
  951. &kCFCopyStringDictionaryKeyCallBacks,
  952. &kCFTypeDictionaryValueCallBacks);
  953. if (!par || !num || !den) {
  954. if (par) CFRelease(par);
  955. if (num) CFRelease(num);
  956. if (den) CFRelease(den);
  957. return AVERROR(ENOMEM);
  958. }
  959. CFDictionarySetValue(
  960. par,
  961. kCMFormatDescriptionKey_PixelAspectRatioHorizontalSpacing,
  962. num);
  963. CFDictionarySetValue(
  964. par,
  965. kCMFormatDescriptionKey_PixelAspectRatioVerticalSpacing,
  966. den);
  967. status = VTSessionSetProperty(vtctx->session,
  968. kVTCompressionPropertyKey_PixelAspectRatio,
  969. par);
  970. CFRelease(par);
  971. CFRelease(num);
  972. CFRelease(den);
  973. if (status) {
  974. av_log(avctx,
  975. AV_LOG_ERROR,
  976. "Error setting pixel aspect ratio to %d:%d: %d.\n",
  977. avctx->sample_aspect_ratio.num,
  978. avctx->sample_aspect_ratio.den,
  979. status);
  980. return AVERROR_EXTERNAL;
  981. }
  982. }
  983. if (vtctx->transfer_function) {
  984. status = VTSessionSetProperty(vtctx->session,
  985. kVTCompressionPropertyKey_TransferFunction,
  986. vtctx->transfer_function);
  987. if (status) {
  988. av_log(avctx, AV_LOG_WARNING, "Could not set transfer function: %d\n", status);
  989. }
  990. }
  991. if (vtctx->ycbcr_matrix) {
  992. status = VTSessionSetProperty(vtctx->session,
  993. kVTCompressionPropertyKey_YCbCrMatrix,
  994. vtctx->ycbcr_matrix);
  995. if (status) {
  996. av_log(avctx, AV_LOG_WARNING, "Could not set ycbcr matrix: %d\n", status);
  997. }
  998. }
  999. if (vtctx->color_primaries) {
  1000. status = VTSessionSetProperty(vtctx->session,
  1001. kVTCompressionPropertyKey_ColorPrimaries,
  1002. vtctx->color_primaries);
  1003. if (status) {
  1004. av_log(avctx, AV_LOG_WARNING, "Could not set color primaries: %d\n", status);
  1005. }
  1006. }
  1007. if (gamma_level) {
  1008. status = VTSessionSetProperty(vtctx->session,
  1009. kCVImageBufferGammaLevelKey,
  1010. gamma_level);
  1011. if (status) {
  1012. av_log(avctx, AV_LOG_WARNING, "Could not set gamma level: %d\n", status);
  1013. }
  1014. }
  1015. if (!vtctx->has_b_frames) {
  1016. status = VTSessionSetProperty(vtctx->session,
  1017. kVTCompressionPropertyKey_AllowFrameReordering,
  1018. kCFBooleanFalse);
  1019. if (status) {
  1020. av_log(avctx, AV_LOG_ERROR, "Error setting 'allow frame reordering' property: %d\n", status);
  1021. return AVERROR_EXTERNAL;
  1022. }
  1023. }
  1024. if (vtctx->entropy != VT_ENTROPY_NOT_SET) {
  1025. CFStringRef entropy = vtctx->entropy == VT_CABAC ?
  1026. compat_keys.kVTH264EntropyMode_CABAC:
  1027. compat_keys.kVTH264EntropyMode_CAVLC;
  1028. status = VTSessionSetProperty(vtctx->session,
  1029. compat_keys.kVTCompressionPropertyKey_H264EntropyMode,
  1030. entropy);
  1031. if (status) {
  1032. av_log(avctx, AV_LOG_ERROR, "Error setting entropy property: %d\n", status);
  1033. }
  1034. }
  1035. if (vtctx->realtime) {
  1036. status = VTSessionSetProperty(vtctx->session,
  1037. compat_keys.kVTCompressionPropertyKey_RealTime,
  1038. kCFBooleanTrue);
  1039. if (status) {
  1040. av_log(avctx, AV_LOG_ERROR, "Error setting realtime property: %d\n", status);
  1041. }
  1042. }
  1043. status = VTCompressionSessionPrepareToEncodeFrames(vtctx->session);
  1044. if (status) {
  1045. av_log(avctx, AV_LOG_ERROR, "Error: cannot prepare encoder: %d\n", status);
  1046. return AVERROR_EXTERNAL;
  1047. }
  1048. return 0;
  1049. }
  1050. static av_cold int vtenc_init(AVCodecContext *avctx)
  1051. {
  1052. CFMutableDictionaryRef enc_info;
  1053. CFMutableDictionaryRef pixel_buffer_info;
  1054. CMVideoCodecType codec_type;
  1055. VTEncContext *vtctx = avctx->priv_data;
  1056. CFStringRef profile_level;
  1057. CFBooleanRef has_b_frames_cfbool;
  1058. CFNumberRef gamma_level = NULL;
  1059. int status;
  1060. pthread_once(&once_ctrl, loadVTEncSymbols);
  1061. codec_type = get_cm_codec_type(avctx->codec_id);
  1062. if (!codec_type) {
  1063. av_log(avctx, AV_LOG_ERROR, "Error: no mapping for AVCodecID %d\n", avctx->codec_id);
  1064. return AVERROR(EINVAL);
  1065. }
  1066. vtctx->codec_id = avctx->codec_id;
  1067. if (vtctx->codec_id == AV_CODEC_ID_H264) {
  1068. vtctx->get_param_set_func = CMVideoFormatDescriptionGetH264ParameterSetAtIndex;
  1069. vtctx->has_b_frames = avctx->max_b_frames > 0;
  1070. if(vtctx->has_b_frames && vtctx->profile == H264_PROF_BASELINE){
  1071. av_log(avctx, AV_LOG_WARNING, "Cannot use B-frames with baseline profile. Output will not contain B-frames.\n");
  1072. vtctx->has_b_frames = false;
  1073. }
  1074. if (vtctx->entropy == VT_CABAC && vtctx->profile == H264_PROF_BASELINE) {
  1075. av_log(avctx, AV_LOG_WARNING, "CABAC entropy requires 'main' or 'high' profile, but baseline was requested. Encode will not use CABAC entropy.\n");
  1076. vtctx->entropy = VT_ENTROPY_NOT_SET;
  1077. }
  1078. if (!get_vt_h264_profile_level(avctx, &profile_level)) return AVERROR(EINVAL);
  1079. } else {
  1080. vtctx->get_param_set_func = compat_keys.CMVideoFormatDescriptionGetHEVCParameterSetAtIndex;
  1081. if (!vtctx->get_param_set_func) return AVERROR(EINVAL);
  1082. if (!get_vt_hevc_profile_level(avctx, &profile_level)) return AVERROR(EINVAL);
  1083. }
  1084. vtctx->session = NULL;
  1085. enc_info = CFDictionaryCreateMutable(
  1086. kCFAllocatorDefault,
  1087. 20,
  1088. &kCFCopyStringDictionaryKeyCallBacks,
  1089. &kCFTypeDictionaryValueCallBacks
  1090. );
  1091. if (!enc_info) return AVERROR(ENOMEM);
  1092. #if !TARGET_OS_IPHONE
  1093. if (!vtctx->allow_sw) {
  1094. CFDictionarySetValue(enc_info,
  1095. compat_keys.kVTVideoEncoderSpecification_RequireHardwareAcceleratedVideoEncoder,
  1096. kCFBooleanTrue);
  1097. } else {
  1098. CFDictionarySetValue(enc_info,
  1099. compat_keys.kVTVideoEncoderSpecification_EnableHardwareAcceleratedVideoEncoder,
  1100. kCFBooleanTrue);
  1101. }
  1102. #endif
  1103. if (avctx->pix_fmt != AV_PIX_FMT_VIDEOTOOLBOX) {
  1104. status = create_cv_pixel_buffer_info(avctx, &pixel_buffer_info);
  1105. if (status)
  1106. goto init_cleanup;
  1107. } else {
  1108. pixel_buffer_info = NULL;
  1109. }
  1110. pthread_mutex_init(&vtctx->lock, NULL);
  1111. pthread_cond_init(&vtctx->cv_sample_sent, NULL);
  1112. vtctx->dts_delta = vtctx->has_b_frames ? -1 : 0;
  1113. get_cv_transfer_function(avctx, &vtctx->transfer_function, &gamma_level);
  1114. get_cv_ycbcr_matrix(avctx, &vtctx->ycbcr_matrix);
  1115. get_cv_color_primaries(avctx, &vtctx->color_primaries);
  1116. if (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
  1117. status = vtenc_populate_extradata(avctx,
  1118. codec_type,
  1119. profile_level,
  1120. gamma_level,
  1121. enc_info,
  1122. pixel_buffer_info);
  1123. if (status)
  1124. goto init_cleanup;
  1125. }
  1126. status = vtenc_create_encoder(avctx,
  1127. codec_type,
  1128. profile_level,
  1129. gamma_level,
  1130. enc_info,
  1131. pixel_buffer_info,
  1132. &vtctx->session);
  1133. if (status < 0)
  1134. goto init_cleanup;
  1135. status = VTSessionCopyProperty(vtctx->session,
  1136. kVTCompressionPropertyKey_AllowFrameReordering,
  1137. kCFAllocatorDefault,
  1138. &has_b_frames_cfbool);
  1139. if (!status && has_b_frames_cfbool) {
  1140. //Some devices don't output B-frames for main profile, even if requested.
  1141. vtctx->has_b_frames = CFBooleanGetValue(has_b_frames_cfbool);
  1142. CFRelease(has_b_frames_cfbool);
  1143. }
  1144. avctx->has_b_frames = vtctx->has_b_frames;
  1145. init_cleanup:
  1146. if (gamma_level)
  1147. CFRelease(gamma_level);
  1148. if (pixel_buffer_info)
  1149. CFRelease(pixel_buffer_info);
  1150. CFRelease(enc_info);
  1151. return status;
  1152. }
  1153. static void vtenc_get_frame_info(CMSampleBufferRef buffer, bool *is_key_frame)
  1154. {
  1155. CFArrayRef attachments;
  1156. CFDictionaryRef attachment;
  1157. CFBooleanRef not_sync;
  1158. CFIndex len;
  1159. attachments = CMSampleBufferGetSampleAttachmentsArray(buffer, false);
  1160. len = !attachments ? 0 : CFArrayGetCount(attachments);
  1161. if (!len) {
  1162. *is_key_frame = true;
  1163. return;
  1164. }
  1165. attachment = CFArrayGetValueAtIndex(attachments, 0);
  1166. if (CFDictionaryGetValueIfPresent(attachment,
  1167. kCMSampleAttachmentKey_NotSync,
  1168. (const void **)&not_sync))
  1169. {
  1170. *is_key_frame = !CFBooleanGetValue(not_sync);
  1171. } else {
  1172. *is_key_frame = true;
  1173. }
  1174. }
  1175. static int is_post_sei_nal_type(int nal_type){
  1176. return nal_type != H264_NAL_SEI &&
  1177. nal_type != H264_NAL_SPS &&
  1178. nal_type != H264_NAL_PPS &&
  1179. nal_type != H264_NAL_AUD;
  1180. }
  1181. /*
  1182. * Finds the sei message start/size of type find_sei_type.
  1183. * If more than one of that type exists, the last one is returned.
  1184. */
  1185. static int find_sei_end(AVCodecContext *avctx,
  1186. uint8_t *nal_data,
  1187. size_t nal_size,
  1188. uint8_t **sei_end)
  1189. {
  1190. int nal_type;
  1191. size_t sei_payload_size = 0;
  1192. int sei_payload_type = 0;
  1193. *sei_end = NULL;
  1194. uint8_t *nal_start = nal_data;
  1195. if (!nal_size)
  1196. return 0;
  1197. nal_type = *nal_data & 0x1F;
  1198. if (nal_type != H264_NAL_SEI)
  1199. return 0;
  1200. nal_data++;
  1201. nal_size--;
  1202. if (nal_data[nal_size - 1] == 0x80)
  1203. nal_size--;
  1204. while (nal_size > 0 && *nal_data > 0) {
  1205. do{
  1206. sei_payload_type += *nal_data;
  1207. nal_data++;
  1208. nal_size--;
  1209. } while (nal_size > 0 && *nal_data == 0xFF);
  1210. if (!nal_size) {
  1211. av_log(avctx, AV_LOG_ERROR, "Unexpected end of SEI NAL Unit parsing type.\n");
  1212. return AVERROR_INVALIDDATA;
  1213. }
  1214. do{
  1215. sei_payload_size += *nal_data;
  1216. nal_data++;
  1217. nal_size--;
  1218. } while (nal_size > 0 && *nal_data == 0xFF);
  1219. if (nal_size < sei_payload_size) {
  1220. av_log(avctx, AV_LOG_ERROR, "Unexpected end of SEI NAL Unit parsing size.\n");
  1221. return AVERROR_INVALIDDATA;
  1222. }
  1223. nal_data += sei_payload_size;
  1224. nal_size -= sei_payload_size;
  1225. }
  1226. *sei_end = nal_data;
  1227. return nal_data - nal_start + 1;
  1228. }
  1229. /**
  1230. * Copies the data inserting emulation prevention bytes as needed.
  1231. * Existing data in the destination can be taken into account by providing
  1232. * dst with a dst_offset > 0.
  1233. *
  1234. * @return The number of bytes copied on success. On failure, the negative of
  1235. * the number of bytes needed to copy src is returned.
  1236. */
  1237. static int copy_emulation_prev(const uint8_t *src,
  1238. size_t src_size,
  1239. uint8_t *dst,
  1240. ssize_t dst_offset,
  1241. size_t dst_size)
  1242. {
  1243. int zeros = 0;
  1244. int wrote_bytes;
  1245. uint8_t* dst_start;
  1246. uint8_t* dst_end = dst + dst_size;
  1247. const uint8_t* src_end = src + src_size;
  1248. int start_at = dst_offset > 2 ? dst_offset - 2 : 0;
  1249. int i;
  1250. for (i = start_at; i < dst_offset && i < dst_size; i++) {
  1251. if (!dst[i])
  1252. zeros++;
  1253. else
  1254. zeros = 0;
  1255. }
  1256. dst += dst_offset;
  1257. dst_start = dst;
  1258. for (; src < src_end; src++, dst++) {
  1259. if (zeros == 2) {
  1260. int insert_ep3_byte = *src <= 3;
  1261. if (insert_ep3_byte) {
  1262. if (dst < dst_end)
  1263. *dst = 3;
  1264. dst++;
  1265. }
  1266. zeros = 0;
  1267. }
  1268. if (dst < dst_end)
  1269. *dst = *src;
  1270. if (!*src)
  1271. zeros++;
  1272. else
  1273. zeros = 0;
  1274. }
  1275. wrote_bytes = dst - dst_start;
  1276. if (dst > dst_end)
  1277. return -wrote_bytes;
  1278. return wrote_bytes;
  1279. }
  1280. static int write_sei(const ExtraSEI *sei,
  1281. int sei_type,
  1282. uint8_t *dst,
  1283. size_t dst_size)
  1284. {
  1285. uint8_t *sei_start = dst;
  1286. size_t remaining_sei_size = sei->size;
  1287. size_t remaining_dst_size = dst_size;
  1288. int header_bytes;
  1289. int bytes_written;
  1290. ssize_t offset;
  1291. if (!remaining_dst_size)
  1292. return AVERROR_BUFFER_TOO_SMALL;
  1293. while (sei_type && remaining_dst_size != 0) {
  1294. int sei_byte = sei_type > 255 ? 255 : sei_type;
  1295. *dst = sei_byte;
  1296. sei_type -= sei_byte;
  1297. dst++;
  1298. remaining_dst_size--;
  1299. }
  1300. if (!dst_size)
  1301. return AVERROR_BUFFER_TOO_SMALL;
  1302. while (remaining_sei_size && remaining_dst_size != 0) {
  1303. int size_byte = remaining_sei_size > 255 ? 255 : remaining_sei_size;
  1304. *dst = size_byte;
  1305. remaining_sei_size -= size_byte;
  1306. dst++;
  1307. remaining_dst_size--;
  1308. }
  1309. if (remaining_dst_size < sei->size)
  1310. return AVERROR_BUFFER_TOO_SMALL;
  1311. header_bytes = dst - sei_start;
  1312. offset = header_bytes;
  1313. bytes_written = copy_emulation_prev(sei->data,
  1314. sei->size,
  1315. sei_start,
  1316. offset,
  1317. dst_size);
  1318. if (bytes_written < 0)
  1319. return AVERROR_BUFFER_TOO_SMALL;
  1320. bytes_written += header_bytes;
  1321. return bytes_written;
  1322. }
  1323. /**
  1324. * Copies NAL units and replaces length codes with
  1325. * H.264 Annex B start codes. On failure, the contents of
  1326. * dst_data may have been modified.
  1327. *
  1328. * @param length_code_size Byte length of each length code
  1329. * @param sample_buffer NAL units prefixed with length codes.
  1330. * @param sei Optional A53 closed captions SEI data.
  1331. * @param dst_data Must be zeroed before calling this function.
  1332. * Contains the copied NAL units prefixed with
  1333. * start codes when the function returns
  1334. * successfully.
  1335. * @param dst_size Length of dst_data
  1336. * @return 0 on success
  1337. * AVERROR_INVALIDDATA if length_code_size is invalid
  1338. * AVERROR_BUFFER_TOO_SMALL if dst_data is too small
  1339. * or if a length_code in src_data specifies data beyond
  1340. * the end of its buffer.
  1341. */
  1342. static int copy_replace_length_codes(
  1343. AVCodecContext *avctx,
  1344. size_t length_code_size,
  1345. CMSampleBufferRef sample_buffer,
  1346. ExtraSEI *sei,
  1347. uint8_t *dst_data,
  1348. size_t dst_size)
  1349. {
  1350. size_t src_size = CMSampleBufferGetTotalSampleSize(sample_buffer);
  1351. size_t remaining_src_size = src_size;
  1352. size_t remaining_dst_size = dst_size;
  1353. size_t src_offset = 0;
  1354. int wrote_sei = 0;
  1355. int status;
  1356. uint8_t size_buf[4];
  1357. uint8_t nal_type;
  1358. CMBlockBufferRef block = CMSampleBufferGetDataBuffer(sample_buffer);
  1359. if (length_code_size > 4) {
  1360. return AVERROR_INVALIDDATA;
  1361. }
  1362. while (remaining_src_size > 0) {
  1363. size_t curr_src_len;
  1364. size_t curr_dst_len;
  1365. size_t box_len = 0;
  1366. size_t i;
  1367. uint8_t *dst_box;
  1368. status = CMBlockBufferCopyDataBytes(block,
  1369. src_offset,
  1370. length_code_size,
  1371. size_buf);
  1372. if (status) {
  1373. av_log(avctx, AV_LOG_ERROR, "Cannot copy length: %d\n", status);
  1374. return AVERROR_EXTERNAL;
  1375. }
  1376. status = CMBlockBufferCopyDataBytes(block,
  1377. src_offset + length_code_size,
  1378. 1,
  1379. &nal_type);
  1380. if (status) {
  1381. av_log(avctx, AV_LOG_ERROR, "Cannot copy type: %d\n", status);
  1382. return AVERROR_EXTERNAL;
  1383. }
  1384. nal_type &= 0x1F;
  1385. for (i = 0; i < length_code_size; i++) {
  1386. box_len <<= 8;
  1387. box_len |= size_buf[i];
  1388. }
  1389. if (sei && !wrote_sei && is_post_sei_nal_type(nal_type)) {
  1390. //No SEI NAL unit - insert.
  1391. int wrote_bytes;
  1392. memcpy(dst_data, start_code, sizeof(start_code));
  1393. dst_data += sizeof(start_code);
  1394. remaining_dst_size -= sizeof(start_code);
  1395. *dst_data = H264_NAL_SEI;
  1396. dst_data++;
  1397. remaining_dst_size--;
  1398. wrote_bytes = write_sei(sei,
  1399. H264_SEI_TYPE_USER_DATA_REGISTERED,
  1400. dst_data,
  1401. remaining_dst_size);
  1402. if (wrote_bytes < 0)
  1403. return wrote_bytes;
  1404. remaining_dst_size -= wrote_bytes;
  1405. dst_data += wrote_bytes;
  1406. if (remaining_dst_size <= 0)
  1407. return AVERROR_BUFFER_TOO_SMALL;
  1408. *dst_data = 0x80;
  1409. dst_data++;
  1410. remaining_dst_size--;
  1411. wrote_sei = 1;
  1412. }
  1413. curr_src_len = box_len + length_code_size;
  1414. curr_dst_len = box_len + sizeof(start_code);
  1415. if (remaining_src_size < curr_src_len) {
  1416. return AVERROR_BUFFER_TOO_SMALL;
  1417. }
  1418. if (remaining_dst_size < curr_dst_len) {
  1419. return AVERROR_BUFFER_TOO_SMALL;
  1420. }
  1421. dst_box = dst_data + sizeof(start_code);
  1422. memcpy(dst_data, start_code, sizeof(start_code));
  1423. status = CMBlockBufferCopyDataBytes(block,
  1424. src_offset + length_code_size,
  1425. box_len,
  1426. dst_box);
  1427. if (status) {
  1428. av_log(avctx, AV_LOG_ERROR, "Cannot copy data: %d\n", status);
  1429. return AVERROR_EXTERNAL;
  1430. }
  1431. if (sei && !wrote_sei && nal_type == H264_NAL_SEI) {
  1432. //Found SEI NAL unit - append.
  1433. int wrote_bytes;
  1434. int old_sei_length;
  1435. int extra_bytes;
  1436. uint8_t *new_sei;
  1437. old_sei_length = find_sei_end(avctx, dst_box, box_len, &new_sei);
  1438. if (old_sei_length < 0)
  1439. return status;
  1440. wrote_bytes = write_sei(sei,
  1441. H264_SEI_TYPE_USER_DATA_REGISTERED,
  1442. new_sei,
  1443. remaining_dst_size - old_sei_length);
  1444. if (wrote_bytes < 0)
  1445. return wrote_bytes;
  1446. if (new_sei + wrote_bytes >= dst_data + remaining_dst_size)
  1447. return AVERROR_BUFFER_TOO_SMALL;
  1448. new_sei[wrote_bytes++] = 0x80;
  1449. extra_bytes = wrote_bytes - (dst_box + box_len - new_sei);
  1450. dst_data += extra_bytes;
  1451. remaining_dst_size -= extra_bytes;
  1452. wrote_sei = 1;
  1453. }
  1454. src_offset += curr_src_len;
  1455. dst_data += curr_dst_len;
  1456. remaining_src_size -= curr_src_len;
  1457. remaining_dst_size -= curr_dst_len;
  1458. }
  1459. return 0;
  1460. }
  1461. /**
  1462. * Returns a sufficient number of bytes to contain the sei data.
  1463. * It may be greater than the minimum required.
  1464. */
  1465. static int get_sei_msg_bytes(const ExtraSEI* sei, int type){
  1466. int copied_size;
  1467. if (sei->size == 0)
  1468. return 0;
  1469. copied_size = -copy_emulation_prev(sei->data,
  1470. sei->size,
  1471. NULL,
  1472. 0,
  1473. 0);
  1474. if ((sei->size % 255) == 0) //may result in an extra byte
  1475. copied_size++;
  1476. return copied_size + sei->size / 255 + 1 + type / 255 + 1;
  1477. }
  1478. static int vtenc_cm_to_avpacket(
  1479. AVCodecContext *avctx,
  1480. CMSampleBufferRef sample_buffer,
  1481. AVPacket *pkt,
  1482. ExtraSEI *sei)
  1483. {
  1484. VTEncContext *vtctx = avctx->priv_data;
  1485. int status;
  1486. bool is_key_frame;
  1487. bool add_header;
  1488. size_t length_code_size;
  1489. size_t header_size = 0;
  1490. size_t in_buf_size;
  1491. size_t out_buf_size;
  1492. size_t sei_nalu_size = 0;
  1493. int64_t dts_delta;
  1494. int64_t time_base_num;
  1495. int nalu_count;
  1496. CMTime pts;
  1497. CMTime dts;
  1498. CMVideoFormatDescriptionRef vid_fmt;
  1499. vtenc_get_frame_info(sample_buffer, &is_key_frame);
  1500. status = get_length_code_size(avctx, sample_buffer, &length_code_size);
  1501. if (status) return status;
  1502. add_header = is_key_frame && !(avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER);
  1503. if (add_header) {
  1504. vid_fmt = CMSampleBufferGetFormatDescription(sample_buffer);
  1505. if (!vid_fmt) {
  1506. av_log(avctx, AV_LOG_ERROR, "Cannot get format description.\n");
  1507. return AVERROR_EXTERNAL;
  1508. }
  1509. int status = get_params_size(avctx, vid_fmt, &header_size);
  1510. if (status) return status;
  1511. }
  1512. status = count_nalus(length_code_size, sample_buffer, &nalu_count);
  1513. if(status)
  1514. return status;
  1515. if (sei) {
  1516. size_t msg_size = get_sei_msg_bytes(sei,
  1517. H264_SEI_TYPE_USER_DATA_REGISTERED);
  1518. sei_nalu_size = sizeof(start_code) + 1 + msg_size + 1;
  1519. }
  1520. in_buf_size = CMSampleBufferGetTotalSampleSize(sample_buffer);
  1521. out_buf_size = header_size +
  1522. in_buf_size +
  1523. sei_nalu_size +
  1524. nalu_count * ((int)sizeof(start_code) - (int)length_code_size);
  1525. status = ff_alloc_packet2(avctx, pkt, out_buf_size, out_buf_size);
  1526. if (status < 0)
  1527. return status;
  1528. if (add_header) {
  1529. status = copy_param_sets(avctx, vid_fmt, pkt->data, out_buf_size);
  1530. if(status) return status;
  1531. }
  1532. status = copy_replace_length_codes(
  1533. avctx,
  1534. length_code_size,
  1535. sample_buffer,
  1536. sei,
  1537. pkt->data + header_size,
  1538. pkt->size - header_size
  1539. );
  1540. if (status) {
  1541. av_log(avctx, AV_LOG_ERROR, "Error copying packet data: %d\n", status);
  1542. return status;
  1543. }
  1544. if (is_key_frame) {
  1545. pkt->flags |= AV_PKT_FLAG_KEY;
  1546. }
  1547. pts = CMSampleBufferGetPresentationTimeStamp(sample_buffer);
  1548. dts = CMSampleBufferGetDecodeTimeStamp (sample_buffer);
  1549. if (CMTIME_IS_INVALID(dts)) {
  1550. if (!vtctx->has_b_frames) {
  1551. dts = pts;
  1552. } else {
  1553. av_log(avctx, AV_LOG_ERROR, "DTS is invalid.\n");
  1554. return AVERROR_EXTERNAL;
  1555. }
  1556. }
  1557. dts_delta = vtctx->dts_delta >= 0 ? vtctx->dts_delta : 0;
  1558. time_base_num = avctx->time_base.num;
  1559. pkt->pts = pts.value / time_base_num;
  1560. pkt->dts = dts.value / time_base_num - dts_delta;
  1561. pkt->size = out_buf_size;
  1562. return 0;
  1563. }
  1564. /*
  1565. * contiguous_buf_size is 0 if not contiguous, and the size of the buffer
  1566. * containing all planes if so.
  1567. */
  1568. static int get_cv_pixel_info(
  1569. AVCodecContext *avctx,
  1570. const AVFrame *frame,
  1571. int *color,
  1572. int *plane_count,
  1573. size_t *widths,
  1574. size_t *heights,
  1575. size_t *strides,
  1576. size_t *contiguous_buf_size)
  1577. {
  1578. VTEncContext *vtctx = avctx->priv_data;
  1579. int av_format = frame->format;
  1580. int av_color_range = frame->color_range;
  1581. int i;
  1582. int range_guessed;
  1583. int status;
  1584. status = get_cv_pixel_format(avctx, av_format, av_color_range, color, &range_guessed);
  1585. if (status) {
  1586. av_log(avctx,
  1587. AV_LOG_ERROR,
  1588. "Could not get pixel format for color format '%s' range '%s'.\n",
  1589. av_get_pix_fmt_name(av_format),
  1590. av_color_range > AVCOL_RANGE_UNSPECIFIED &&
  1591. av_color_range < AVCOL_RANGE_NB ?
  1592. av_color_range_name(av_color_range) :
  1593. "Unknown");
  1594. return AVERROR(EINVAL);
  1595. }
  1596. if (range_guessed) {
  1597. if (!vtctx->warned_color_range) {
  1598. vtctx->warned_color_range = true;
  1599. av_log(avctx,
  1600. AV_LOG_WARNING,
  1601. "Color range not set for %s. Using MPEG range.\n",
  1602. av_get_pix_fmt_name(av_format));
  1603. }
  1604. }
  1605. switch (av_format) {
  1606. case AV_PIX_FMT_NV12:
  1607. *plane_count = 2;
  1608. widths [0] = avctx->width;
  1609. heights[0] = avctx->height;
  1610. strides[0] = frame ? frame->linesize[0] : avctx->width;
  1611. widths [1] = (avctx->width + 1) / 2;
  1612. heights[1] = (avctx->height + 1) / 2;
  1613. strides[1] = frame ? frame->linesize[1] : (avctx->width + 1) & -2;
  1614. break;
  1615. case AV_PIX_FMT_YUV420P:
  1616. *plane_count = 3;
  1617. widths [0] = avctx->width;
  1618. heights[0] = avctx->height;
  1619. strides[0] = frame ? frame->linesize[0] : avctx->width;
  1620. widths [1] = (avctx->width + 1) / 2;
  1621. heights[1] = (avctx->height + 1) / 2;
  1622. strides[1] = frame ? frame->linesize[1] : (avctx->width + 1) / 2;
  1623. widths [2] = (avctx->width + 1) / 2;
  1624. heights[2] = (avctx->height + 1) / 2;
  1625. strides[2] = frame ? frame->linesize[2] : (avctx->width + 1) / 2;
  1626. break;
  1627. default:
  1628. av_log(
  1629. avctx,
  1630. AV_LOG_ERROR,
  1631. "Could not get frame format info for color %d range %d.\n",
  1632. av_format,
  1633. av_color_range);
  1634. return AVERROR(EINVAL);
  1635. }
  1636. *contiguous_buf_size = 0;
  1637. for (i = 0; i < *plane_count; i++) {
  1638. if (i < *plane_count - 1 &&
  1639. frame->data[i] + strides[i] * heights[i] != frame->data[i + 1]) {
  1640. *contiguous_buf_size = 0;
  1641. break;
  1642. }
  1643. *contiguous_buf_size += strides[i] * heights[i];
  1644. }
  1645. return 0;
  1646. }
  1647. #if !TARGET_OS_IPHONE
  1648. //Not used on iOS - frame is always copied.
  1649. static void free_avframe(
  1650. void *release_ctx,
  1651. const void *data,
  1652. size_t size,
  1653. size_t plane_count,
  1654. const void *plane_addresses[])
  1655. {
  1656. AVFrame *frame = release_ctx;
  1657. av_frame_free(&frame);
  1658. }
  1659. #else
  1660. //Not used on OSX - frame is never copied.
  1661. static int copy_avframe_to_pixel_buffer(AVCodecContext *avctx,
  1662. const AVFrame *frame,
  1663. CVPixelBufferRef cv_img,
  1664. const size_t *plane_strides,
  1665. const size_t *plane_rows)
  1666. {
  1667. int i, j;
  1668. size_t plane_count;
  1669. int status;
  1670. int rows;
  1671. int src_stride;
  1672. int dst_stride;
  1673. uint8_t *src_addr;
  1674. uint8_t *dst_addr;
  1675. size_t copy_bytes;
  1676. status = CVPixelBufferLockBaseAddress(cv_img, 0);
  1677. if (status) {
  1678. av_log(
  1679. avctx,
  1680. AV_LOG_ERROR,
  1681. "Error: Could not lock base address of CVPixelBuffer: %d.\n",
  1682. status
  1683. );
  1684. }
  1685. if (CVPixelBufferIsPlanar(cv_img)) {
  1686. plane_count = CVPixelBufferGetPlaneCount(cv_img);
  1687. for (i = 0; frame->data[i]; i++) {
  1688. if (i == plane_count) {
  1689. CVPixelBufferUnlockBaseAddress(cv_img, 0);
  1690. av_log(avctx,
  1691. AV_LOG_ERROR,
  1692. "Error: different number of planes in AVFrame and CVPixelBuffer.\n"
  1693. );
  1694. return AVERROR_EXTERNAL;
  1695. }
  1696. dst_addr = (uint8_t*)CVPixelBufferGetBaseAddressOfPlane(cv_img, i);
  1697. src_addr = (uint8_t*)frame->data[i];
  1698. dst_stride = CVPixelBufferGetBytesPerRowOfPlane(cv_img, i);
  1699. src_stride = plane_strides[i];
  1700. rows = plane_rows[i];
  1701. if (dst_stride == src_stride) {
  1702. memcpy(dst_addr, src_addr, src_stride * rows);
  1703. } else {
  1704. copy_bytes = dst_stride < src_stride ? dst_stride : src_stride;
  1705. for (j = 0; j < rows; j++) {
  1706. memcpy(dst_addr + j * dst_stride, src_addr + j * src_stride, copy_bytes);
  1707. }
  1708. }
  1709. }
  1710. } else {
  1711. if (frame->data[1]) {
  1712. CVPixelBufferUnlockBaseAddress(cv_img, 0);
  1713. av_log(avctx,
  1714. AV_LOG_ERROR,
  1715. "Error: different number of planes in AVFrame and non-planar CVPixelBuffer.\n"
  1716. );
  1717. return AVERROR_EXTERNAL;
  1718. }
  1719. dst_addr = (uint8_t*)CVPixelBufferGetBaseAddress(cv_img);
  1720. src_addr = (uint8_t*)frame->data[0];
  1721. dst_stride = CVPixelBufferGetBytesPerRow(cv_img);
  1722. src_stride = plane_strides[0];
  1723. rows = plane_rows[0];
  1724. if (dst_stride == src_stride) {
  1725. memcpy(dst_addr, src_addr, src_stride * rows);
  1726. } else {
  1727. copy_bytes = dst_stride < src_stride ? dst_stride : src_stride;
  1728. for (j = 0; j < rows; j++) {
  1729. memcpy(dst_addr + j * dst_stride, src_addr + j * src_stride, copy_bytes);
  1730. }
  1731. }
  1732. }
  1733. status = CVPixelBufferUnlockBaseAddress(cv_img, 0);
  1734. if (status) {
  1735. av_log(avctx, AV_LOG_ERROR, "Error: Could not unlock CVPixelBuffer base address: %d.\n", status);
  1736. return AVERROR_EXTERNAL;
  1737. }
  1738. return 0;
  1739. }
  1740. #endif //!TARGET_OS_IPHONE
  1741. static int create_cv_pixel_buffer(AVCodecContext *avctx,
  1742. const AVFrame *frame,
  1743. CVPixelBufferRef *cv_img)
  1744. {
  1745. int plane_count;
  1746. int color;
  1747. size_t widths [AV_NUM_DATA_POINTERS];
  1748. size_t heights[AV_NUM_DATA_POINTERS];
  1749. size_t strides[AV_NUM_DATA_POINTERS];
  1750. int status;
  1751. size_t contiguous_buf_size;
  1752. #if TARGET_OS_IPHONE
  1753. CVPixelBufferPoolRef pix_buf_pool;
  1754. VTEncContext* vtctx = avctx->priv_data;
  1755. #else
  1756. CFMutableDictionaryRef pix_buf_attachments = CFDictionaryCreateMutable(
  1757. kCFAllocatorDefault,
  1758. 10,
  1759. &kCFCopyStringDictionaryKeyCallBacks,
  1760. &kCFTypeDictionaryValueCallBacks);
  1761. if (!pix_buf_attachments) return AVERROR(ENOMEM);
  1762. #endif
  1763. if (avctx->pix_fmt == AV_PIX_FMT_VIDEOTOOLBOX) {
  1764. av_assert0(frame->format == AV_PIX_FMT_VIDEOTOOLBOX);
  1765. *cv_img = (CVPixelBufferRef)frame->data[3];
  1766. av_assert0(*cv_img);
  1767. CFRetain(*cv_img);
  1768. return 0;
  1769. }
  1770. memset(widths, 0, sizeof(widths));
  1771. memset(heights, 0, sizeof(heights));
  1772. memset(strides, 0, sizeof(strides));
  1773. status = get_cv_pixel_info(
  1774. avctx,
  1775. frame,
  1776. &color,
  1777. &plane_count,
  1778. widths,
  1779. heights,
  1780. strides,
  1781. &contiguous_buf_size
  1782. );
  1783. if (status) {
  1784. av_log(
  1785. avctx,
  1786. AV_LOG_ERROR,
  1787. "Error: Cannot convert format %d color_range %d: %d\n",
  1788. frame->format,
  1789. frame->color_range,
  1790. status
  1791. );
  1792. return AVERROR_EXTERNAL;
  1793. }
  1794. #if TARGET_OS_IPHONE
  1795. pix_buf_pool = VTCompressionSessionGetPixelBufferPool(vtctx->session);
  1796. if (!pix_buf_pool) {
  1797. av_log(avctx, AV_LOG_ERROR, "Could not get pixel buffer pool.\n");
  1798. return AVERROR_EXTERNAL;
  1799. }
  1800. status = CVPixelBufferPoolCreatePixelBuffer(NULL,
  1801. pix_buf_pool,
  1802. cv_img);
  1803. if (status) {
  1804. av_log(avctx, AV_LOG_ERROR, "Could not create pixel buffer from pool: %d.\n", status);
  1805. return AVERROR_EXTERNAL;
  1806. }
  1807. status = copy_avframe_to_pixel_buffer(avctx, frame, *cv_img, strides, heights);
  1808. if (status) {
  1809. CFRelease(*cv_img);
  1810. *cv_img = NULL;
  1811. return status;
  1812. }
  1813. #else
  1814. AVFrame *enc_frame = av_frame_alloc();
  1815. if (!enc_frame) return AVERROR(ENOMEM);
  1816. status = av_frame_ref(enc_frame, frame);
  1817. if (status) {
  1818. av_frame_free(&enc_frame);
  1819. return status;
  1820. }
  1821. status = CVPixelBufferCreateWithPlanarBytes(
  1822. kCFAllocatorDefault,
  1823. enc_frame->width,
  1824. enc_frame->height,
  1825. color,
  1826. NULL,
  1827. contiguous_buf_size,
  1828. plane_count,
  1829. (void **)enc_frame->data,
  1830. widths,
  1831. heights,
  1832. strides,
  1833. free_avframe,
  1834. enc_frame,
  1835. NULL,
  1836. cv_img
  1837. );
  1838. add_color_attr(avctx, pix_buf_attachments);
  1839. CVBufferSetAttachments(*cv_img, pix_buf_attachments, kCVAttachmentMode_ShouldPropagate);
  1840. CFRelease(pix_buf_attachments);
  1841. if (status) {
  1842. av_log(avctx, AV_LOG_ERROR, "Error: Could not create CVPixelBuffer: %d\n", status);
  1843. return AVERROR_EXTERNAL;
  1844. }
  1845. #endif
  1846. return 0;
  1847. }
  1848. static int create_encoder_dict_h264(const AVFrame *frame,
  1849. CFDictionaryRef* dict_out)
  1850. {
  1851. CFDictionaryRef dict = NULL;
  1852. if (frame->pict_type == AV_PICTURE_TYPE_I) {
  1853. const void *keys[] = { kVTEncodeFrameOptionKey_ForceKeyFrame };
  1854. const void *vals[] = { kCFBooleanTrue };
  1855. dict = CFDictionaryCreate(NULL, keys, vals, 1, NULL, NULL);
  1856. if(!dict) return AVERROR(ENOMEM);
  1857. }
  1858. *dict_out = dict;
  1859. return 0;
  1860. }
  1861. static int vtenc_send_frame(AVCodecContext *avctx,
  1862. VTEncContext *vtctx,
  1863. const AVFrame *frame)
  1864. {
  1865. CMTime time;
  1866. CFDictionaryRef frame_dict;
  1867. CVPixelBufferRef cv_img = NULL;
  1868. AVFrameSideData *side_data = NULL;
  1869. ExtraSEI *sei = NULL;
  1870. int status = create_cv_pixel_buffer(avctx, frame, &cv_img);
  1871. if (status) return status;
  1872. status = create_encoder_dict_h264(frame, &frame_dict);
  1873. if (status) {
  1874. CFRelease(cv_img);
  1875. return status;
  1876. }
  1877. side_data = av_frame_get_side_data(frame, AV_FRAME_DATA_A53_CC);
  1878. if (vtctx->a53_cc && side_data && side_data->size) {
  1879. sei = av_mallocz(sizeof(*sei));
  1880. if (!sei) {
  1881. av_log(avctx, AV_LOG_ERROR, "Not enough memory for closed captions, skipping\n");
  1882. } else {
  1883. int ret = ff_alloc_a53_sei(frame, 0, &sei->data, &sei->size);
  1884. if (ret < 0) {
  1885. av_log(avctx, AV_LOG_ERROR, "Not enough memory for closed captions, skipping\n");
  1886. av_free(sei);
  1887. sei = NULL;
  1888. }
  1889. }
  1890. }
  1891. time = CMTimeMake(frame->pts * avctx->time_base.num, avctx->time_base.den);
  1892. status = VTCompressionSessionEncodeFrame(
  1893. vtctx->session,
  1894. cv_img,
  1895. time,
  1896. kCMTimeInvalid,
  1897. frame_dict,
  1898. sei,
  1899. NULL
  1900. );
  1901. if (frame_dict) CFRelease(frame_dict);
  1902. CFRelease(cv_img);
  1903. if (status) {
  1904. av_log(avctx, AV_LOG_ERROR, "Error: cannot encode frame: %d\n", status);
  1905. return AVERROR_EXTERNAL;
  1906. }
  1907. return 0;
  1908. }
  1909. static av_cold int vtenc_frame(
  1910. AVCodecContext *avctx,
  1911. AVPacket *pkt,
  1912. const AVFrame *frame,
  1913. int *got_packet)
  1914. {
  1915. VTEncContext *vtctx = avctx->priv_data;
  1916. bool get_frame;
  1917. int status;
  1918. CMSampleBufferRef buf = NULL;
  1919. ExtraSEI *sei = NULL;
  1920. if (frame) {
  1921. status = vtenc_send_frame(avctx, vtctx, frame);
  1922. if (status) {
  1923. status = AVERROR_EXTERNAL;
  1924. goto end_nopkt;
  1925. }
  1926. if (vtctx->frame_ct_in == 0) {
  1927. vtctx->first_pts = frame->pts;
  1928. } else if(vtctx->frame_ct_in == 1 && vtctx->has_b_frames) {
  1929. vtctx->dts_delta = frame->pts - vtctx->first_pts;
  1930. }
  1931. vtctx->frame_ct_in++;
  1932. } else if(!vtctx->flushing) {
  1933. vtctx->flushing = true;
  1934. status = VTCompressionSessionCompleteFrames(vtctx->session,
  1935. kCMTimeIndefinite);
  1936. if (status) {
  1937. av_log(avctx, AV_LOG_ERROR, "Error flushing frames: %d\n", status);
  1938. status = AVERROR_EXTERNAL;
  1939. goto end_nopkt;
  1940. }
  1941. }
  1942. *got_packet = 0;
  1943. get_frame = vtctx->dts_delta >= 0 || !frame;
  1944. if (!get_frame) {
  1945. status = 0;
  1946. goto end_nopkt;
  1947. }
  1948. status = vtenc_q_pop(vtctx, !frame, &buf, &sei);
  1949. if (status) goto end_nopkt;
  1950. if (!buf) goto end_nopkt;
  1951. status = vtenc_cm_to_avpacket(avctx, buf, pkt, sei);
  1952. if (sei) {
  1953. if (sei->data) av_free(sei->data);
  1954. av_free(sei);
  1955. }
  1956. CFRelease(buf);
  1957. if (status) goto end_nopkt;
  1958. *got_packet = 1;
  1959. return 0;
  1960. end_nopkt:
  1961. av_packet_unref(pkt);
  1962. return status;
  1963. }
  1964. static int vtenc_populate_extradata(AVCodecContext *avctx,
  1965. CMVideoCodecType codec_type,
  1966. CFStringRef profile_level,
  1967. CFNumberRef gamma_level,
  1968. CFDictionaryRef enc_info,
  1969. CFDictionaryRef pixel_buffer_info)
  1970. {
  1971. VTEncContext *vtctx = avctx->priv_data;
  1972. AVFrame *frame = av_frame_alloc();
  1973. int y_size = avctx->width * avctx->height;
  1974. int chroma_size = (avctx->width / 2) * (avctx->height / 2);
  1975. CMSampleBufferRef buf = NULL;
  1976. int status;
  1977. if (!frame)
  1978. return AVERROR(ENOMEM);
  1979. frame->buf[0] = av_buffer_alloc(y_size + 2 * chroma_size);
  1980. if(!frame->buf[0]){
  1981. status = AVERROR(ENOMEM);
  1982. goto pe_cleanup;
  1983. }
  1984. status = vtenc_create_encoder(avctx,
  1985. codec_type,
  1986. profile_level,
  1987. gamma_level,
  1988. enc_info,
  1989. pixel_buffer_info,
  1990. &vtctx->session);
  1991. if (status)
  1992. goto pe_cleanup;
  1993. frame->data[0] = frame->buf[0]->data;
  1994. memset(frame->data[0], 0, y_size);
  1995. frame->data[1] = frame->buf[0]->data + y_size;
  1996. memset(frame->data[1], 128, chroma_size);
  1997. if (avctx->pix_fmt == AV_PIX_FMT_YUV420P) {
  1998. frame->data[2] = frame->buf[0]->data + y_size + chroma_size;
  1999. memset(frame->data[2], 128, chroma_size);
  2000. }
  2001. frame->linesize[0] = avctx->width;
  2002. if (avctx->pix_fmt == AV_PIX_FMT_YUV420P) {
  2003. frame->linesize[1] =
  2004. frame->linesize[2] = (avctx->width + 1) / 2;
  2005. } else {
  2006. frame->linesize[1] = (avctx->width + 1) / 2;
  2007. }
  2008. frame->format = avctx->pix_fmt;
  2009. frame->width = avctx->width;
  2010. frame->height = avctx->height;
  2011. frame->colorspace = avctx->colorspace;
  2012. frame->color_range = avctx->color_range;
  2013. frame->color_trc = avctx->color_trc;
  2014. frame->color_primaries = avctx->color_primaries;
  2015. frame->pts = 0;
  2016. status = vtenc_send_frame(avctx, vtctx, frame);
  2017. if (status) {
  2018. av_log(avctx, AV_LOG_ERROR, "Error sending frame: %d\n", status);
  2019. goto pe_cleanup;
  2020. }
  2021. //Populates extradata - output frames are flushed and param sets are available.
  2022. status = VTCompressionSessionCompleteFrames(vtctx->session,
  2023. kCMTimeIndefinite);
  2024. if (status)
  2025. goto pe_cleanup;
  2026. status = vtenc_q_pop(vtctx, 0, &buf, NULL);
  2027. if (status) {
  2028. av_log(avctx, AV_LOG_ERROR, "popping: %d\n", status);
  2029. goto pe_cleanup;
  2030. }
  2031. CFRelease(buf);
  2032. pe_cleanup:
  2033. if(vtctx->session)
  2034. CFRelease(vtctx->session);
  2035. vtctx->session = NULL;
  2036. vtctx->frame_ct_out = 0;
  2037. av_frame_unref(frame);
  2038. av_frame_free(&frame);
  2039. av_assert0(status != 0 || (avctx->extradata && avctx->extradata_size > 0));
  2040. return status;
  2041. }
  2042. static av_cold int vtenc_close(AVCodecContext *avctx)
  2043. {
  2044. VTEncContext *vtctx = avctx->priv_data;
  2045. pthread_cond_destroy(&vtctx->cv_sample_sent);
  2046. pthread_mutex_destroy(&vtctx->lock);
  2047. if(!vtctx->session) return 0;
  2048. VTCompressionSessionCompleteFrames(vtctx->session,
  2049. kCMTimeIndefinite);
  2050. clear_frame_queue(vtctx);
  2051. CFRelease(vtctx->session);
  2052. vtctx->session = NULL;
  2053. if (vtctx->color_primaries) {
  2054. CFRelease(vtctx->color_primaries);
  2055. vtctx->color_primaries = NULL;
  2056. }
  2057. if (vtctx->transfer_function) {
  2058. CFRelease(vtctx->transfer_function);
  2059. vtctx->transfer_function = NULL;
  2060. }
  2061. if (vtctx->ycbcr_matrix) {
  2062. CFRelease(vtctx->ycbcr_matrix);
  2063. vtctx->ycbcr_matrix = NULL;
  2064. }
  2065. return 0;
  2066. }
  2067. static const enum AVPixelFormat pix_fmts[] = {
  2068. AV_PIX_FMT_VIDEOTOOLBOX,
  2069. AV_PIX_FMT_NV12,
  2070. AV_PIX_FMT_YUV420P,
  2071. AV_PIX_FMT_NONE
  2072. };
  2073. #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
  2074. #define COMMON_OPTIONS \
  2075. { "allow_sw", "Allow software encoding", OFFSET(allow_sw), AV_OPT_TYPE_BOOL, \
  2076. { .i64 = 0 }, 0, 1, VE }, \
  2077. { "realtime", "Hint that encoding should happen in real-time if not faster (e.g. capturing from camera).", \
  2078. OFFSET(realtime), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VE }, \
  2079. { "frames_before", "Other frames will come before the frames in this session. This helps smooth concatenation issues.", \
  2080. OFFSET(frames_before), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VE }, \
  2081. { "frames_after", "Other frames will come after the frames in this session. This helps smooth concatenation issues.", \
  2082. OFFSET(frames_after), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VE },
  2083. #define OFFSET(x) offsetof(VTEncContext, x)
  2084. static const AVOption h264_options[] = {
  2085. { "profile", "Profile", OFFSET(profile), AV_OPT_TYPE_INT, { .i64 = H264_PROF_AUTO }, H264_PROF_AUTO, H264_PROF_COUNT, VE, "profile" },
  2086. { "baseline", "Baseline Profile", 0, AV_OPT_TYPE_CONST, { .i64 = H264_PROF_BASELINE }, INT_MIN, INT_MAX, VE, "profile" },
  2087. { "main", "Main Profile", 0, AV_OPT_TYPE_CONST, { .i64 = H264_PROF_MAIN }, INT_MIN, INT_MAX, VE, "profile" },
  2088. { "high", "High Profile", 0, AV_OPT_TYPE_CONST, { .i64 = H264_PROF_HIGH }, INT_MIN, INT_MAX, VE, "profile" },
  2089. { "level", "Level", OFFSET(level), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 52, VE, "level" },
  2090. { "1.3", "Level 1.3, only available with Baseline Profile", 0, AV_OPT_TYPE_CONST, { .i64 = 13 }, INT_MIN, INT_MAX, VE, "level" },
  2091. { "3.0", "Level 3.0", 0, AV_OPT_TYPE_CONST, { .i64 = 30 }, INT_MIN, INT_MAX, VE, "level" },
  2092. { "3.1", "Level 3.1", 0, AV_OPT_TYPE_CONST, { .i64 = 31 }, INT_MIN, INT_MAX, VE, "level" },
  2093. { "3.2", "Level 3.2", 0, AV_OPT_TYPE_CONST, { .i64 = 32 }, INT_MIN, INT_MAX, VE, "level" },
  2094. { "4.0", "Level 4.0", 0, AV_OPT_TYPE_CONST, { .i64 = 40 }, INT_MIN, INT_MAX, VE, "level" },
  2095. { "4.1", "Level 4.1", 0, AV_OPT_TYPE_CONST, { .i64 = 41 }, INT_MIN, INT_MAX, VE, "level" },
  2096. { "4.2", "Level 4.2", 0, AV_OPT_TYPE_CONST, { .i64 = 42 }, INT_MIN, INT_MAX, VE, "level" },
  2097. { "5.0", "Level 5.0", 0, AV_OPT_TYPE_CONST, { .i64 = 50 }, INT_MIN, INT_MAX, VE, "level" },
  2098. { "5.1", "Level 5.1", 0, AV_OPT_TYPE_CONST, { .i64 = 51 }, INT_MIN, INT_MAX, VE, "level" },
  2099. { "5.2", "Level 5.2", 0, AV_OPT_TYPE_CONST, { .i64 = 52 }, INT_MIN, INT_MAX, VE, "level" },
  2100. { "coder", "Entropy coding", OFFSET(entropy), AV_OPT_TYPE_INT, { .i64 = VT_ENTROPY_NOT_SET }, VT_ENTROPY_NOT_SET, VT_CABAC, VE, "coder" },
  2101. { "cavlc", "CAVLC entropy coding", 0, AV_OPT_TYPE_CONST, { .i64 = VT_CAVLC }, INT_MIN, INT_MAX, VE, "coder" },
  2102. { "vlc", "CAVLC entropy coding", 0, AV_OPT_TYPE_CONST, { .i64 = VT_CAVLC }, INT_MIN, INT_MAX, VE, "coder" },
  2103. { "cabac", "CABAC entropy coding", 0, AV_OPT_TYPE_CONST, { .i64 = VT_CABAC }, INT_MIN, INT_MAX, VE, "coder" },
  2104. { "ac", "CABAC entropy coding", 0, AV_OPT_TYPE_CONST, { .i64 = VT_CABAC }, INT_MIN, INT_MAX, VE, "coder" },
  2105. { "a53cc", "Use A53 Closed Captions (if available)", OFFSET(a53_cc), AV_OPT_TYPE_BOOL, {.i64 = 1}, 0, 1, VE },
  2106. COMMON_OPTIONS
  2107. { NULL },
  2108. };
  2109. static const AVClass h264_videotoolbox_class = {
  2110. .class_name = "h264_videotoolbox",
  2111. .item_name = av_default_item_name,
  2112. .option = h264_options,
  2113. .version = LIBAVUTIL_VERSION_INT,
  2114. };
  2115. AVCodec ff_h264_videotoolbox_encoder = {
  2116. .name = "h264_videotoolbox",
  2117. .long_name = NULL_IF_CONFIG_SMALL("VideoToolbox H.264 Encoder"),
  2118. .type = AVMEDIA_TYPE_VIDEO,
  2119. .id = AV_CODEC_ID_H264,
  2120. .priv_data_size = sizeof(VTEncContext),
  2121. .pix_fmts = pix_fmts,
  2122. .init = vtenc_init,
  2123. .encode2 = vtenc_frame,
  2124. .close = vtenc_close,
  2125. .capabilities = AV_CODEC_CAP_DELAY,
  2126. .priv_class = &h264_videotoolbox_class,
  2127. .caps_internal = FF_CODEC_CAP_INIT_THREADSAFE |
  2128. FF_CODEC_CAP_INIT_CLEANUP,
  2129. };
  2130. static const AVOption hevc_options[] = {
  2131. { "profile", "Profile", OFFSET(profile), AV_OPT_TYPE_INT, { .i64 = HEVC_PROF_AUTO }, HEVC_PROF_AUTO, HEVC_PROF_COUNT, VE, "profile" },
  2132. { "main", "Main Profile", 0, AV_OPT_TYPE_CONST, { .i64 = HEVC_PROF_MAIN }, INT_MIN, INT_MAX, VE, "profile" },
  2133. { "main10", "Main10 Profile", 0, AV_OPT_TYPE_CONST, { .i64 = HEVC_PROF_MAIN10 }, INT_MIN, INT_MAX, VE, "profile" },
  2134. COMMON_OPTIONS
  2135. { NULL },
  2136. };
  2137. static const AVClass hevc_videotoolbox_class = {
  2138. .class_name = "hevc_videotoolbox",
  2139. .item_name = av_default_item_name,
  2140. .option = hevc_options,
  2141. .version = LIBAVUTIL_VERSION_INT,
  2142. };
  2143. AVCodec ff_hevc_videotoolbox_encoder = {
  2144. .name = "hevc_videotoolbox",
  2145. .long_name = NULL_IF_CONFIG_SMALL("VideoToolbox H.265 Encoder"),
  2146. .type = AVMEDIA_TYPE_VIDEO,
  2147. .id = AV_CODEC_ID_HEVC,
  2148. .priv_data_size = sizeof(VTEncContext),
  2149. .pix_fmts = pix_fmts,
  2150. .init = vtenc_init,
  2151. .encode2 = vtenc_frame,
  2152. .close = vtenc_close,
  2153. .capabilities = AV_CODEC_CAP_DELAY | AV_CODEC_CAP_HARDWARE,
  2154. .priv_class = &hevc_videotoolbox_class,
  2155. .caps_internal = FF_CODEC_CAP_INIT_THREADSAFE |
  2156. FF_CODEC_CAP_INIT_CLEANUP,
  2157. .wrapper_name = "videotoolbox",
  2158. };