FFmpeg
videotoolboxenc.c
Go to the documentation of this file.
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 
21 #include <VideoToolbox/VideoToolbox.h>
22 #include <CoreVideo/CoreVideo.h>
23 #include <CoreMedia/CoreMedia.h>
24 #include <TargetConditionals.h>
25 #include <Availability.h>
26 #include "avcodec.h"
27 #include "libavutil/mem.h"
28 #include "libavutil/opt.h"
29 #include "libavutil/avassert.h"
30 #include "libavutil/avstring.h"
31 #include "libavcodec/avcodec.h"
32 #include "libavutil/pixdesc.h"
34 #include "codec_internal.h"
35 #include "internal.h"
36 #include <pthread.h>
37 #include "atsc_a53.h"
38 #include "encode.h"
39 #include "h264.h"
40 #include "h264_sei.h"
41 #include "hwconfig.h"
42 #include <dlfcn.h>
43 
44 #if !HAVE_KCMVIDEOCODECTYPE_HEVC
45 enum { kCMVideoCodecType_HEVC = 'hvc1' };
46 #endif
47 
48 #if !HAVE_KCMVIDEOCODECTYPE_HEVCWITHALPHA
50 #endif
51 
52 #if !HAVE_KCVPIXELFORMATTYPE_420YPCBCR10BIPLANARVIDEORANGE
55 #endif
56 
57 #if !HAVE_KVTQPMODULATIONLEVEL_DEFAULT
60 #endif
61 
62 #ifndef TARGET_CPU_ARM64
63 # define TARGET_CPU_ARM64 0
64 #endif
65 
66 typedef OSStatus (*getParameterSetAtIndex)(CMFormatDescriptionRef videoDesc,
67  size_t parameterSetIndex,
68  const uint8_t **parameterSetPointerOut,
69  size_t *parameterSetSizeOut,
70  size_t *parameterSetCountOut,
71  int *NALUnitHeaderLengthOut);
72 
73 /*
74  * Symbols that aren't available in MacOS 10.8 and iOS 8.0 need to be accessed
75  * from compat_keys, or it will cause compiler errors when compiling for older
76  * OS versions.
77  *
78  * For example, kVTCompressionPropertyKey_H264EntropyMode was added in
79  * MacOS 10.9. If this constant were used directly, a compiler would generate
80  * an error when it has access to the MacOS 10.8 headers, but does not have
81  * 10.9 headers.
82  *
83  * Runtime errors will still occur when unknown keys are set. A warning is
84  * logged and encoding continues where possible.
85  *
86  * When adding new symbols, they should be loaded/set in loadVTEncSymbols().
87  */
88 static struct{
92 
96 
120 
124 
131 
140 
142 } compat_keys;
143 
144 #define GET_SYM(symbol, defaultVal) \
145 do{ \
146  CFStringRef* handle = (CFStringRef*)dlsym(RTLD_DEFAULT, #symbol); \
147  if(!handle) \
148  compat_keys.symbol = CFSTR(defaultVal); \
149  else \
150  compat_keys.symbol = *handle; \
151 }while(0)
152 
154 
155 static void loadVTEncSymbols(void){
156  compat_keys.CMVideoFormatDescriptionGetHEVCParameterSetAtIndex =
157  (getParameterSetAtIndex)dlsym(
158  RTLD_DEFAULT,
159  "CMVideoFormatDescriptionGetHEVCParameterSetAtIndex"
160  );
161 
165 
169 
170  GET_SYM(kVTProfileLevel_H264_Baseline_4_0, "H264_Baseline_4_0");
171  GET_SYM(kVTProfileLevel_H264_Baseline_4_2, "H264_Baseline_4_2");
172  GET_SYM(kVTProfileLevel_H264_Baseline_5_0, "H264_Baseline_5_0");
173  GET_SYM(kVTProfileLevel_H264_Baseline_5_1, "H264_Baseline_5_1");
174  GET_SYM(kVTProfileLevel_H264_Baseline_5_2, "H264_Baseline_5_2");
175  GET_SYM(kVTProfileLevel_H264_Baseline_AutoLevel, "H264_Baseline_AutoLevel");
176  GET_SYM(kVTProfileLevel_H264_Main_4_2, "H264_Main_4_2");
177  GET_SYM(kVTProfileLevel_H264_Main_5_1, "H264_Main_5_1");
178  GET_SYM(kVTProfileLevel_H264_Main_5_2, "H264_Main_5_2");
179  GET_SYM(kVTProfileLevel_H264_Main_AutoLevel, "H264_Main_AutoLevel");
180  GET_SYM(kVTProfileLevel_H264_High_3_0, "H264_High_3_0");
181  GET_SYM(kVTProfileLevel_H264_High_3_1, "H264_High_3_1");
182  GET_SYM(kVTProfileLevel_H264_High_3_2, "H264_High_3_2");
183  GET_SYM(kVTProfileLevel_H264_High_4_0, "H264_High_4_0");
184  GET_SYM(kVTProfileLevel_H264_High_4_1, "H264_High_4_1");
185  GET_SYM(kVTProfileLevel_H264_High_4_2, "H264_High_4_2");
186  GET_SYM(kVTProfileLevel_H264_High_5_1, "H264_High_5_1");
187  GET_SYM(kVTProfileLevel_H264_High_5_2, "H264_High_5_2");
188  GET_SYM(kVTProfileLevel_H264_High_AutoLevel, "H264_High_AutoLevel");
189  GET_SYM(kVTProfileLevel_H264_Extended_5_0, "H264_Extended_5_0");
190  GET_SYM(kVTProfileLevel_H264_Extended_AutoLevel, "H264_Extended_AutoLevel");
191  GET_SYM(kVTProfileLevel_H264_ConstrainedBaseline_AutoLevel, "H264_ConstrainedBaseline_AutoLevel");
192  GET_SYM(kVTProfileLevel_H264_ConstrainedHigh_AutoLevel, "H264_ConstrainedHigh_AutoLevel");
193 
194  GET_SYM(kVTProfileLevel_HEVC_Main_AutoLevel, "HEVC_Main_AutoLevel");
195  GET_SYM(kVTProfileLevel_HEVC_Main10_AutoLevel, "HEVC_Main10_AutoLevel");
196  GET_SYM(kVTProfileLevel_HEVC_Main42210_AutoLevel, "HEVC_Main42210_AutoLevel");
197 
200  "TargetQualityForAlpha");
202  "PrioritizeEncodingSpeedOverQuality");
205 
207  "EnableHardwareAcceleratedVideoEncoder");
209  "RequireHardwareAcceleratedVideoEncoder");
211  "EnableLowLatencyRateControl");
214  "MaximizePowerEfficiency");
216  "ReferenceBufferCount");
220 }
221 
222 #define H264_PROFILE_CONSTRAINED_HIGH (AV_PROFILE_H264_HIGH | AV_PROFILE_H264_CONSTRAINED)
223 
224 typedef enum VTH264Entropy{
228 } VTH264Entropy;
229 
230 static const uint8_t start_code[] = { 0, 0, 0, 1 };
231 
232 typedef struct ExtraSEI {
233  void *data;
234  size_t size;
235 } ExtraSEI;
236 
237 typedef struct BufNode {
238  CMSampleBufferRef cm_buffer;
241  struct BufNode* next;
242 } BufNode;
243 
244 typedef struct VTEncContext {
245  AVClass *class;
247  VTCompressionSessionRef session;
248  CFDictionaryRef supported_props;
249  CFStringRef ycbcr_matrix;
250  CFStringRef color_primaries;
251  CFStringRef transfer_function;
253 
256 
258 
261 
264 
267 
268  int profile;
269  int level;
270  int entropy;
271  int realtime;
275 
276  int allow_sw;
280 
281  bool flushing;
284 
285  /* can't be bool type since AVOption will access it as int */
286  int a53_cc;
287 
292 } VTEncContext;
293 
295 {
296  if (!info)
297  return;
298 
299  av_free(info->sei.data);
300  if (info->cm_buffer)
301  CFRelease(info->cm_buffer);
302  av_buffer_unref(&info->frame_buf);
303  av_free(info);
304 }
305 
306 static int vt_dump_encoder(AVCodecContext *avctx)
307 {
308  VTEncContext *vtctx = avctx->priv_data;
309  CFStringRef encoder_id = NULL;
310  int status;
311  CFIndex length, max_size;
312  char *name;
313 
314  status = VTSessionCopyProperty(vtctx->session,
315  compat_keys.kVTCompressionPropertyKey_EncoderID,
316  kCFAllocatorDefault,
317  &encoder_id);
318  // OK if not supported
319  if (status != noErr)
320  return 0;
321 
322  length = CFStringGetLength(encoder_id);
323  max_size = CFStringGetMaximumSizeForEncoding(length, kCFStringEncodingUTF8);
324  name = av_malloc(max_size);
325  if (!name) {
326  CFRelease(encoder_id);
327  return AVERROR(ENOMEM);
328  }
329 
330  CFStringGetCString(encoder_id,
331  name,
332  max_size,
333  kCFStringEncodingUTF8);
334  av_log(avctx, AV_LOG_DEBUG, "Init the encoder: %s\n", name);
335  av_freep(&name);
336  CFRelease(encoder_id);
337 
338  return 0;
339 }
340 
341 static int vtenc_populate_extradata(AVCodecContext *avctx,
342  CMVideoCodecType codec_type,
343  CFStringRef profile_level,
344  CFNumberRef gamma_level,
345  CFDictionaryRef enc_info,
346  CFDictionaryRef pixel_buffer_info);
347 
348 /**
349  * NULL-safe release of *refPtr, and sets value to NULL.
350  */
351 static void vt_release_num(CFNumberRef* refPtr){
352  if (!*refPtr) {
353  return;
354  }
355 
356  CFRelease(*refPtr);
357  *refPtr = NULL;
358 }
359 
360 static void set_async_error(VTEncContext *vtctx, int err)
361 {
362  BufNode *info;
363 
364  pthread_mutex_lock(&vtctx->lock);
365 
366  vtctx->async_error = err;
367 
368  info = vtctx->q_head;
369  vtctx->q_head = vtctx->q_tail = NULL;
370 
371  while (info) {
372  BufNode *next = info->next;
374  info = next;
375  }
376 
377  pthread_mutex_unlock(&vtctx->lock);
378 }
379 
380 static void clear_frame_queue(VTEncContext *vtctx)
381 {
382  set_async_error(vtctx, 0);
383 }
384 
385 static void vtenc_reset(VTEncContext *vtctx)
386 {
387  if (vtctx->session) {
388  CFRelease(vtctx->session);
389  vtctx->session = NULL;
390  }
391 
392  if (vtctx->supported_props) {
393  CFRelease(vtctx->supported_props);
394  vtctx->supported_props = NULL;
395  }
396 
397  if (vtctx->color_primaries) {
398  CFRelease(vtctx->color_primaries);
399  vtctx->color_primaries = NULL;
400  }
401 
402  if (vtctx->transfer_function) {
403  CFRelease(vtctx->transfer_function);
404  vtctx->transfer_function = NULL;
405  }
406 
407  if (vtctx->ycbcr_matrix) {
408  CFRelease(vtctx->ycbcr_matrix);
409  vtctx->ycbcr_matrix = NULL;
410  }
411 }
412 
413 static int vtenc_q_pop(VTEncContext *vtctx, bool wait, CMSampleBufferRef *buf, ExtraSEI *sei)
414 {
415  BufNode *info;
416 
417  pthread_mutex_lock(&vtctx->lock);
418 
419  if (vtctx->async_error) {
420  pthread_mutex_unlock(&vtctx->lock);
421  return vtctx->async_error;
422  }
423 
424  if (vtctx->flushing && vtctx->frame_ct_in == vtctx->frame_ct_out) {
425  *buf = NULL;
426 
427  pthread_mutex_unlock(&vtctx->lock);
428  return 0;
429  }
430 
431  while (!vtctx->q_head && !vtctx->async_error && wait && !vtctx->flushing) {
432  pthread_cond_wait(&vtctx->cv_sample_sent, &vtctx->lock);
433  }
434 
435  if (!vtctx->q_head) {
436  pthread_mutex_unlock(&vtctx->lock);
437  *buf = NULL;
438  return 0;
439  }
440 
441  info = vtctx->q_head;
442  vtctx->q_head = vtctx->q_head->next;
443  if (!vtctx->q_head) {
444  vtctx->q_tail = NULL;
445  }
446 
447  vtctx->frame_ct_out++;
448  pthread_mutex_unlock(&vtctx->lock);
449 
450  *buf = info->cm_buffer;
451  info->cm_buffer = NULL;
452  if (sei && *buf) {
453  *sei = info->sei;
454  info->sei = (ExtraSEI) {0};
455  }
457 
458  return 0;
459 }
460 
461 static void vtenc_q_push(VTEncContext *vtctx, BufNode *info)
462 {
463  pthread_mutex_lock(&vtctx->lock);
464 
465  if (!vtctx->q_head) {
466  vtctx->q_head = info;
467  } else {
468  vtctx->q_tail->next = info;
469  }
470 
471  vtctx->q_tail = info;
472 
474  pthread_mutex_unlock(&vtctx->lock);
475 }
476 
477 static int count_nalus(size_t length_code_size,
478  CMSampleBufferRef sample_buffer,
479  int *count)
480 {
481  size_t offset = 0;
482  int status;
483  int nalu_ct = 0;
484  uint8_t size_buf[4];
485  size_t src_size = CMSampleBufferGetTotalSampleSize(sample_buffer);
486  CMBlockBufferRef block = CMSampleBufferGetDataBuffer(sample_buffer);
487 
488  if (length_code_size > 4)
489  return AVERROR_INVALIDDATA;
490 
491  while (offset < src_size) {
492  size_t curr_src_len;
493  size_t box_len = 0;
494  size_t i;
495 
496  status = CMBlockBufferCopyDataBytes(block,
497  offset,
498  length_code_size,
499  size_buf);
500 
501  if (status != kCMBlockBufferNoErr) {
502  return AVERROR_EXTERNAL;
503  }
504 
505  for (i = 0; i < length_code_size; i++) {
506  box_len <<= 8;
507  box_len |= size_buf[i];
508  }
509 
510  curr_src_len = box_len + length_code_size;
511  offset += curr_src_len;
512 
513  nalu_ct++;
514  }
515 
516  *count = nalu_ct;
517  return 0;
518 }
519 
520 static CMVideoCodecType get_cm_codec_type(AVCodecContext *avctx,
521  int profile,
522  double alpha_quality)
523 {
525  switch (avctx->codec_id) {
526  case AV_CODEC_ID_H264: return kCMVideoCodecType_H264;
527  case AV_CODEC_ID_HEVC:
528  if (desc && (desc->flags & AV_PIX_FMT_FLAG_ALPHA) && alpha_quality > 0.0) {
530  }
531  return kCMVideoCodecType_HEVC;
532  case AV_CODEC_ID_PRORES:
533  if (desc && (desc->flags & AV_PIX_FMT_FLAG_ALPHA))
534  avctx->bits_per_coded_sample = 32;
535  switch (profile) {
537  return MKBETAG('a','p','c','o'); // kCMVideoCodecType_AppleProRes422Proxy
539  return MKBETAG('a','p','c','s'); // kCMVideoCodecType_AppleProRes422LT
541  return MKBETAG('a','p','c','n'); // kCMVideoCodecType_AppleProRes422
543  return MKBETAG('a','p','c','h'); // kCMVideoCodecType_AppleProRes422HQ
545  return MKBETAG('a','p','4','h'); // kCMVideoCodecType_AppleProRes4444
547  return MKBETAG('a','p','4','x'); // kCMVideoCodecType_AppleProRes4444XQ
548 
549  default:
550  av_log(avctx, AV_LOG_ERROR, "Unknown profile ID: %d, using auto\n", profile);
551  case AV_PROFILE_UNKNOWN:
552  if (desc &&
553  ((desc->flags & AV_PIX_FMT_FLAG_ALPHA) ||
554  desc->log2_chroma_w == 0))
555  return MKBETAG('a','p','4','h'); // kCMVideoCodecType_AppleProRes4444
556  else
557  return MKBETAG('a','p','c','n'); // kCMVideoCodecType_AppleProRes422
558  }
559  default: return 0;
560  }
561 }
562 
563 /**
564  * Get the parameter sets from a CMSampleBufferRef.
565  * @param dst If *dst isn't NULL, the parameters are copied into existing
566  * memory. *dst_size must be set accordingly when *dst != NULL.
567  * If *dst is NULL, it will be allocated.
568  * In all cases, *dst_size is set to the number of bytes used starting
569  * at *dst.
570  */
571 static int get_params_size(
572  AVCodecContext *avctx,
573  CMVideoFormatDescriptionRef vid_fmt,
574  size_t *size)
575 {
576  VTEncContext *vtctx = avctx->priv_data;
577  size_t total_size = 0;
578  size_t ps_count;
579  int is_count_bad = 0;
580  size_t i;
581  int status;
582  status = vtctx->get_param_set_func(vid_fmt,
583  0,
584  NULL,
585  NULL,
586  &ps_count,
587  NULL);
588  if (status) {
589  is_count_bad = 1;
590  ps_count = 0;
591  status = 0;
592  }
593 
594  for (i = 0; i < ps_count || is_count_bad; i++) {
595  const uint8_t *ps;
596  size_t ps_size;
597  status = vtctx->get_param_set_func(vid_fmt,
598  i,
599  &ps,
600  &ps_size,
601  NULL,
602  NULL);
603  if (status) {
604  /*
605  * When ps_count is invalid, status != 0 ends the loop normally
606  * unless we didn't get any parameter sets.
607  */
608  if (i > 0 && is_count_bad) status = 0;
609 
610  break;
611  }
612 
613  total_size += ps_size + sizeof(start_code);
614  }
615 
616  if (status) {
617  av_log(avctx, AV_LOG_ERROR, "Error getting parameter set sizes: %d\n", status);
618  return AVERROR_EXTERNAL;
619  }
620 
621  *size = total_size;
622  return 0;
623 }
624 
625 static int copy_param_sets(
626  AVCodecContext *avctx,
627  CMVideoFormatDescriptionRef vid_fmt,
628  uint8_t *dst,
629  size_t dst_size)
630 {
631  VTEncContext *vtctx = avctx->priv_data;
632  size_t ps_count;
633  int is_count_bad = 0;
634  int status;
635  size_t offset = 0;
636  size_t i;
637 
638  status = vtctx->get_param_set_func(vid_fmt,
639  0,
640  NULL,
641  NULL,
642  &ps_count,
643  NULL);
644  if (status) {
645  is_count_bad = 1;
646  ps_count = 0;
647  status = 0;
648  }
649 
650 
651  for (i = 0; i < ps_count || is_count_bad; i++) {
652  const uint8_t *ps;
653  size_t ps_size;
654  size_t next_offset;
655 
656  status = vtctx->get_param_set_func(vid_fmt,
657  i,
658  &ps,
659  &ps_size,
660  NULL,
661  NULL);
662  if (status) {
663  if (i > 0 && is_count_bad) status = 0;
664 
665  break;
666  }
667 
668  next_offset = offset + sizeof(start_code) + ps_size;
669  if (dst_size < next_offset) {
670  av_log(avctx, AV_LOG_ERROR, "Error: buffer too small for parameter sets.\n");
672  }
673 
674  memcpy(dst + offset, start_code, sizeof(start_code));
675  offset += sizeof(start_code);
676 
677  memcpy(dst + offset, ps, ps_size);
678  offset = next_offset;
679  }
680 
681  if (status) {
682  av_log(avctx, AV_LOG_ERROR, "Error getting parameter set data: %d\n", status);
683  return AVERROR_EXTERNAL;
684  }
685 
686  return 0;
687 }
688 
689 static int set_extradata(AVCodecContext *avctx, CMSampleBufferRef sample_buffer)
690 {
691  VTEncContext *vtctx = avctx->priv_data;
692  CMVideoFormatDescriptionRef vid_fmt;
693  size_t total_size;
694  int status;
695 
696  vid_fmt = CMSampleBufferGetFormatDescription(sample_buffer);
697  if (!vid_fmt) {
698  av_log(avctx, AV_LOG_ERROR, "No video format.\n");
699  return AVERROR_EXTERNAL;
700  }
701 
702  if (vtctx->get_param_set_func) {
703  status = get_params_size(avctx, vid_fmt, &total_size);
704  if (status) {
705  av_log(avctx, AV_LOG_ERROR, "Could not get parameter sets.\n");
706  return status;
707  }
708 
709  avctx->extradata = av_mallocz(total_size + AV_INPUT_BUFFER_PADDING_SIZE);
710  if (!avctx->extradata) {
711  return AVERROR(ENOMEM);
712  }
713  avctx->extradata_size = total_size;
714 
715  status = copy_param_sets(avctx, vid_fmt, avctx->extradata, total_size);
716 
717  if (status) {
718  av_log(avctx, AV_LOG_ERROR, "Could not copy param sets.\n");
719  return status;
720  }
721  } else {
722  CFDataRef data = CMFormatDescriptionGetExtension(vid_fmt, kCMFormatDescriptionExtension_VerbatimSampleDescription);
723  if (data && CFGetTypeID(data) == CFDataGetTypeID()) {
724  CFIndex size = CFDataGetLength(data);
725 
727  if (!avctx->extradata)
728  return AVERROR(ENOMEM);
729  avctx->extradata_size = size;
730 
731  CFDataGetBytes(data, CFRangeMake(0, size), avctx->extradata);
732  }
733  }
734 
735  return 0;
736 }
737 
739  void *ctx,
740  void *sourceFrameCtx,
741  OSStatus status,
742  VTEncodeInfoFlags flags,
743  CMSampleBufferRef sample_buffer)
744 {
745  AVCodecContext *avctx = ctx;
746  VTEncContext *vtctx = avctx->priv_data;
747  BufNode *info = sourceFrameCtx;
748 
749  av_buffer_unref(&info->frame_buf);
750  if (vtctx->async_error) {
752  return;
753  }
754 
755  if (status) {
757  av_log(avctx, AV_LOG_ERROR, "Error encoding frame: %d\n", (int)status);
759  return;
760  }
761 
762  if (!sample_buffer) {
763  return;
764  }
765 
766  CFRetain(sample_buffer);
767  info->cm_buffer = sample_buffer;
768 
769  if (!avctx->extradata && (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER)) {
770  int set_status = set_extradata(avctx, sample_buffer);
771  if (set_status) {
773  set_async_error(vtctx, set_status);
774  return;
775  }
776  }
777 
778  vtenc_q_push(vtctx, info);
779 }
780 
782  AVCodecContext *avctx,
783  CMSampleBufferRef sample_buffer,
784  size_t *size)
785 {
786  VTEncContext *vtctx = avctx->priv_data;
787  CMVideoFormatDescriptionRef vid_fmt;
788  int isize;
789  int status;
790 
791  vid_fmt = CMSampleBufferGetFormatDescription(sample_buffer);
792  if (!vid_fmt) {
793  av_log(avctx, AV_LOG_ERROR, "Error getting buffer format description.\n");
794  return AVERROR_EXTERNAL;
795  }
796 
797  status = vtctx->get_param_set_func(vid_fmt,
798  0,
799  NULL,
800  NULL,
801  NULL,
802  &isize);
803  if (status) {
804  av_log(avctx, AV_LOG_ERROR, "Error getting length code size: %d\n", status);
805  return AVERROR_EXTERNAL;
806  }
807 
808  *size = isize;
809  return 0;
810 }
811 
812 /*
813  * Returns true on success.
814  *
815  * If profile_level_val is NULL and this method returns true, don't specify the
816  * profile/level to the encoder.
817  */
819  CFStringRef *profile_level_val)
820 {
821  VTEncContext *vtctx = avctx->priv_data;
822  int profile = vtctx->profile;
823 
824  if (profile == AV_PROFILE_UNKNOWN && vtctx->level) {
825  //Need to pick a profile if level is not auto-selected.
827  }
828 
829  *profile_level_val = NULL;
830 
831  switch (profile) {
832  case AV_PROFILE_UNKNOWN:
833  return true;
834 
836  switch (vtctx->level) {
837  case 0: *profile_level_val =
838  compat_keys.kVTProfileLevel_H264_Baseline_AutoLevel; break;
839  case 13: *profile_level_val = kVTProfileLevel_H264_Baseline_1_3; break;
840  case 30: *profile_level_val = kVTProfileLevel_H264_Baseline_3_0; break;
841  case 31: *profile_level_val = kVTProfileLevel_H264_Baseline_3_1; break;
842  case 32: *profile_level_val = kVTProfileLevel_H264_Baseline_3_2; break;
843  case 40: *profile_level_val =
844  compat_keys.kVTProfileLevel_H264_Baseline_4_0; break;
845  case 41: *profile_level_val = kVTProfileLevel_H264_Baseline_4_1; break;
846  case 42: *profile_level_val =
847  compat_keys.kVTProfileLevel_H264_Baseline_4_2; break;
848  case 50: *profile_level_val =
849  compat_keys.kVTProfileLevel_H264_Baseline_5_0; break;
850  case 51: *profile_level_val =
851  compat_keys.kVTProfileLevel_H264_Baseline_5_1; break;
852  case 52: *profile_level_val =
853  compat_keys.kVTProfileLevel_H264_Baseline_5_2; break;
854  }
855  break;
856 
858  *profile_level_val = compat_keys.kVTProfileLevel_H264_ConstrainedBaseline_AutoLevel;
859 
860  if (vtctx->level != 0) {
861  av_log(avctx,
863  "Level is auto-selected when constrained-baseline "
864  "profile is used. The output may be encoded with a "
865  "different level.\n");
866  }
867  break;
868 
870  switch (vtctx->level) {
871  case 0: *profile_level_val =
872  compat_keys.kVTProfileLevel_H264_Main_AutoLevel; break;
873  case 30: *profile_level_val = kVTProfileLevel_H264_Main_3_0; break;
874  case 31: *profile_level_val = kVTProfileLevel_H264_Main_3_1; break;
875  case 32: *profile_level_val = kVTProfileLevel_H264_Main_3_2; break;
876  case 40: *profile_level_val = kVTProfileLevel_H264_Main_4_0; break;
877  case 41: *profile_level_val = kVTProfileLevel_H264_Main_4_1; break;
878  case 42: *profile_level_val =
879  compat_keys.kVTProfileLevel_H264_Main_4_2; break;
880  case 50: *profile_level_val = kVTProfileLevel_H264_Main_5_0; break;
881  case 51: *profile_level_val =
882  compat_keys.kVTProfileLevel_H264_Main_5_1; break;
883  case 52: *profile_level_val =
884  compat_keys.kVTProfileLevel_H264_Main_5_2; break;
885  }
886  break;
887 
889  *profile_level_val = compat_keys.kVTProfileLevel_H264_ConstrainedHigh_AutoLevel;
890 
891  if (vtctx->level != 0) {
892  av_log(avctx,
894  "Level is auto-selected when constrained-high profile "
895  "is used. The output may be encoded with a different "
896  "level.\n");
897  }
898  break;
899 
901  switch (vtctx->level) {
902  case 0: *profile_level_val =
903  compat_keys.kVTProfileLevel_H264_High_AutoLevel; break;
904  case 30: *profile_level_val =
905  compat_keys.kVTProfileLevel_H264_High_3_0; break;
906  case 31: *profile_level_val =
907  compat_keys.kVTProfileLevel_H264_High_3_1; break;
908  case 32: *profile_level_val =
909  compat_keys.kVTProfileLevel_H264_High_3_2; break;
910  case 40: *profile_level_val =
911  compat_keys.kVTProfileLevel_H264_High_4_0; break;
912  case 41: *profile_level_val =
913  compat_keys.kVTProfileLevel_H264_High_4_1; break;
914  case 42: *profile_level_val =
915  compat_keys.kVTProfileLevel_H264_High_4_2; break;
916  case 50: *profile_level_val = kVTProfileLevel_H264_High_5_0; break;
917  case 51: *profile_level_val =
918  compat_keys.kVTProfileLevel_H264_High_5_1; break;
919  case 52: *profile_level_val =
920  compat_keys.kVTProfileLevel_H264_High_5_2; break;
921  }
922  break;
924  switch (vtctx->level) {
925  case 0: *profile_level_val =
926  compat_keys.kVTProfileLevel_H264_Extended_AutoLevel; break;
927  case 50: *profile_level_val =
928  compat_keys.kVTProfileLevel_H264_Extended_5_0; break;
929  }
930  break;
931  }
932 
933  if (!*profile_level_val) {
934  av_log(avctx, AV_LOG_ERROR, "Invalid Profile/Level.\n");
935  return false;
936  }
937 
938  return true;
939 }
940 
941 /*
942  * Returns true on success.
943  *
944  * If profile_level_val is NULL and this method returns true, don't specify the
945  * profile/level to the encoder.
946  */
948  CFStringRef *profile_level_val)
949 {
950  VTEncContext *vtctx = avctx->priv_data;
951  int profile = vtctx->profile;
953  avctx->pix_fmt == AV_PIX_FMT_VIDEOTOOLBOX ? avctx->sw_pix_fmt
954  : avctx->pix_fmt);
955  int bit_depth = desc ? desc->comp[0].depth : 0;
956 
957  *profile_level_val = NULL;
958 
959  switch (profile) {
960  case AV_PROFILE_UNKNOWN:
961  // Set profile automatically if user don't specify
962  if (bit_depth == 10) {
963  *profile_level_val =
964  compat_keys.kVTProfileLevel_HEVC_Main10_AutoLevel;
965  break;
966  }
967  return true;
969  if (bit_depth > 0 && bit_depth != 8)
970  av_log(avctx, AV_LOG_WARNING,
971  "main profile with %d bit input\n", bit_depth);
972  *profile_level_val =
973  compat_keys.kVTProfileLevel_HEVC_Main_AutoLevel;
974  break;
976  if (bit_depth > 0 && bit_depth != 10) {
977  av_log(avctx, AV_LOG_ERROR,
978  "Invalid main10 profile with %d bit input\n", bit_depth);
979  return false;
980  }
981  *profile_level_val =
982  compat_keys.kVTProfileLevel_HEVC_Main10_AutoLevel;
983  break;
985  // only main42210 is supported, omit depth and chroma subsampling
986  *profile_level_val =
987  compat_keys.kVTProfileLevel_HEVC_Main42210_AutoLevel;
988  break;
989  }
990 
991  if (!*profile_level_val) {
992  av_log(avctx, AV_LOG_ERROR, "Invalid Profile/Level.\n");
993  return false;
994  }
995 
996  return true;
997 }
998 
1000  enum AVPixelFormat fmt,
1001  enum AVColorRange range,
1002  int* av_pixel_format,
1003  int* range_guessed)
1004 {
1005  const char *range_name;
1006  if (range_guessed) *range_guessed = range != AVCOL_RANGE_MPEG &&
1008 
1009  //MPEG range is used when no range is set
1011  if (*av_pixel_format)
1012  return 0;
1013 
1014  range_name = av_color_range_name(range);
1015  av_log(avctx, AV_LOG_ERROR,
1016  "Could not get pixel format for color format '%s' range '%s'.\n",
1017  av_get_pix_fmt_name(fmt),
1018  range_name ? range_name : "Unknown");
1019 
1020  return AVERROR(EINVAL);
1021 }
1022 
1023 static void add_color_attr(AVCodecContext *avctx, CFMutableDictionaryRef dict) {
1024  VTEncContext *vtctx = avctx->priv_data;
1025 
1026  if (vtctx->color_primaries) {
1027  CFDictionarySetValue(dict,
1028  kCVImageBufferColorPrimariesKey,
1029  vtctx->color_primaries);
1030  }
1031 
1032  if (vtctx->transfer_function) {
1033  CFDictionarySetValue(dict,
1034  kCVImageBufferTransferFunctionKey,
1035  vtctx->transfer_function);
1036  }
1037 
1038  if (vtctx->ycbcr_matrix) {
1039  CFDictionarySetValue(dict,
1040  kCVImageBufferYCbCrMatrixKey,
1041  vtctx->ycbcr_matrix);
1042  }
1043 }
1044 
1046  CFMutableDictionaryRef* dict)
1047 {
1048  CFNumberRef cv_color_format_num = NULL;
1049  CFNumberRef width_num = NULL;
1050  CFNumberRef height_num = NULL;
1051  CFMutableDictionaryRef pixel_buffer_info = NULL;
1052  int cv_color_format;
1053  int status = get_cv_pixel_format(avctx,
1054  avctx->pix_fmt,
1055  avctx->color_range,
1056  &cv_color_format,
1057  NULL);
1058  if (status) return status;
1059 
1060  pixel_buffer_info = CFDictionaryCreateMutable(
1061  kCFAllocatorDefault,
1062  20,
1063  &kCFCopyStringDictionaryKeyCallBacks,
1064  &kCFTypeDictionaryValueCallBacks);
1065 
1066  if (!pixel_buffer_info) goto pbinfo_nomem;
1067 
1068  cv_color_format_num = CFNumberCreate(kCFAllocatorDefault,
1069  kCFNumberSInt32Type,
1070  &cv_color_format);
1071  if (!cv_color_format_num) goto pbinfo_nomem;
1072 
1073  CFDictionarySetValue(pixel_buffer_info,
1074  kCVPixelBufferPixelFormatTypeKey,
1075  cv_color_format_num);
1076  vt_release_num(&cv_color_format_num);
1077 
1078  width_num = CFNumberCreate(kCFAllocatorDefault,
1079  kCFNumberSInt32Type,
1080  &avctx->width);
1081  if (!width_num) goto pbinfo_nomem;
1082 
1083  CFDictionarySetValue(pixel_buffer_info,
1084  kCVPixelBufferWidthKey,
1085  width_num);
1086  vt_release_num(&width_num);
1087 
1088  height_num = CFNumberCreate(kCFAllocatorDefault,
1089  kCFNumberSInt32Type,
1090  &avctx->height);
1091  if (!height_num) goto pbinfo_nomem;
1092 
1093  CFDictionarySetValue(pixel_buffer_info,
1094  kCVPixelBufferHeightKey,
1095  height_num);
1096  vt_release_num(&height_num);
1097 
1098  add_color_attr(avctx, pixel_buffer_info);
1099 
1100  *dict = pixel_buffer_info;
1101  return 0;
1102 
1103 pbinfo_nomem:
1104  vt_release_num(&cv_color_format_num);
1105  vt_release_num(&width_num);
1106  vt_release_num(&height_num);
1107  if (pixel_buffer_info) CFRelease(pixel_buffer_info);
1108 
1109  return AVERROR(ENOMEM);
1110 }
1111 
1112 static int get_cv_gamma(AVCodecContext *avctx,
1113  CFNumberRef *gamma_level)
1114 {
1115  enum AVColorTransferCharacteristic trc = avctx->color_trc;
1116  Float32 gamma = 0;
1117  *gamma_level = NULL;
1118 
1119  if (trc == AVCOL_TRC_GAMMA22)
1120  gamma = 2.2;
1121  else if (trc == AVCOL_TRC_GAMMA28)
1122  gamma = 2.8;
1123 
1124  if (gamma != 0)
1125  *gamma_level = CFNumberCreate(NULL, kCFNumberFloat32Type, &gamma);
1126  return 0;
1127 }
1128 
1129 // constant quality only on Macs with Apple Silicon
1130 static bool vtenc_qscale_enabled(void)
1131 {
1132  return !TARGET_OS_IPHONE && TARGET_CPU_ARM64;
1133 }
1134 
1136  CFStringRef key,
1137  const char *print_option_name,
1138  CFTypeRef value) {
1139  int status;
1140  VTEncContext *vtctx = avctx->priv_data;
1141 
1142  status = VTSessionSetProperty(vtctx->session, key, value);
1143  if (status == kVTPropertyNotSupportedErr) {
1144  av_log(avctx,
1145  AV_LOG_INFO,
1146  "This device does not support the %s option. Value ignored.\n",
1147  print_option_name);
1148  } else if (status != 0) {
1149  av_log(avctx,
1150  AV_LOG_ERROR,
1151  "Error setting %s: Error %d\n",
1152  print_option_name,
1153  status);
1154  }
1155 }
1156 
1158  CFStringRef key,
1159  const char* print_option_name,
1160  int value) {
1161  CFNumberRef value_cfnum = CFNumberCreate(kCFAllocatorDefault,
1162  kCFNumberIntType,
1163  &value);
1164 
1165  if (value_cfnum == NULL) {
1166  return AVERROR(ENOMEM);
1167  }
1168 
1169  set_encoder_property_or_log(avctx, key, print_option_name, value_cfnum);
1170 
1171  CFRelease(value_cfnum);
1172 
1173  return 0;
1174 }
1175 
1177  CMVideoCodecType codec_type,
1178  CFStringRef profile_level,
1179  CFNumberRef gamma_level,
1180  CFDictionaryRef enc_info,
1181  CFDictionaryRef pixel_buffer_info,
1182  bool constant_bit_rate,
1183  VTCompressionSessionRef *session)
1184 {
1185  VTEncContext *vtctx = avctx->priv_data;
1186  SInt32 bit_rate = avctx->bit_rate;
1187  SInt32 max_rate = avctx->rc_max_rate;
1188  Float32 quality = avctx->global_quality / FF_QP2LAMBDA;
1189  CFNumberRef bit_rate_num;
1190  CFNumberRef quality_num;
1191  CFNumberRef bytes_per_second;
1192  CFNumberRef one_second;
1193  CFArrayRef data_rate_limits;
1194  int64_t bytes_per_second_value = 0;
1195  int64_t one_second_value = 0;
1196  void *nums[2];
1197 
1198  int status = VTCompressionSessionCreate(kCFAllocatorDefault,
1199  avctx->width,
1200  avctx->height,
1201  codec_type,
1202  enc_info,
1203  pixel_buffer_info,
1204  kCFAllocatorDefault,
1206  avctx,
1207  session);
1208 
1209  if (status || !vtctx->session) {
1210  av_log(avctx, AV_LOG_ERROR, "Error: cannot create compression session: %d\n", status);
1211 
1212 #if !TARGET_OS_IPHONE
1213  if (!vtctx->allow_sw) {
1214  av_log(avctx, AV_LOG_ERROR, "Try -allow_sw 1. The hardware encoder may be busy, or not supported.\n");
1215  }
1216 #endif
1217 
1218  return AVERROR_EXTERNAL;
1219  }
1220 
1221 #if defined (MAC_OS_X_VERSION_10_13) && (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_13)
1222  if (__builtin_available(macOS 10.13, *)) {
1223  if (vtctx->supported_props) {
1224  CFRelease(vtctx->supported_props);
1225  vtctx->supported_props = NULL;
1226  }
1227  status = VTCopySupportedPropertyDictionaryForEncoder(avctx->width,
1228  avctx->height,
1229  codec_type,
1230  enc_info,
1231  NULL,
1232  &vtctx->supported_props);
1233 
1234  if (status != noErr) {
1235  av_log(avctx, AV_LOG_ERROR,"Error retrieving the supported property dictionary err=%"PRId64"\n", (int64_t)status);
1236  return AVERROR_EXTERNAL;
1237  }
1238  }
1239 #endif
1240 
1241  status = vt_dump_encoder(avctx);
1242  if (status < 0)
1243  return status;
1244 
1245  if (avctx->flags & AV_CODEC_FLAG_QSCALE && !vtenc_qscale_enabled()) {
1246  av_log(avctx, AV_LOG_ERROR, "Error: -q:v qscale not available for encoder. Use -b:v bitrate instead.\n");
1247  return AVERROR_EXTERNAL;
1248  }
1249 
1250  if (avctx->flags & AV_CODEC_FLAG_QSCALE) {
1251  quality = quality >= 100 ? 1.0 : quality / 100;
1252  quality_num = CFNumberCreate(kCFAllocatorDefault,
1253  kCFNumberFloat32Type,
1254  &quality);
1255  if (!quality_num) return AVERROR(ENOMEM);
1256 
1257  status = VTSessionSetProperty(vtctx->session,
1258  kVTCompressionPropertyKey_Quality,
1259  quality_num);
1260  CFRelease(quality_num);
1261  } else if (avctx->codec_id != AV_CODEC_ID_PRORES) {
1262  bit_rate_num = CFNumberCreate(kCFAllocatorDefault,
1263  kCFNumberSInt32Type,
1264  &bit_rate);
1265  if (!bit_rate_num) return AVERROR(ENOMEM);
1266 
1267  if (constant_bit_rate) {
1268  status = VTSessionSetProperty(vtctx->session,
1269  compat_keys.kVTCompressionPropertyKey_ConstantBitRate,
1270  bit_rate_num);
1271  if (status == kVTPropertyNotSupportedErr) {
1272  av_log(avctx, AV_LOG_ERROR, "Error: -constant_bit_rate true is not supported by the encoder.\n");
1273  return AVERROR_EXTERNAL;
1274  }
1275  } else {
1276  status = VTSessionSetProperty(vtctx->session,
1277  kVTCompressionPropertyKey_AverageBitRate,
1278  bit_rate_num);
1279  }
1280 
1281  CFRelease(bit_rate_num);
1282  }
1283 
1284  if (status) {
1285  av_log(avctx, AV_LOG_ERROR, "Error setting bitrate property: %d\n", status);
1286  return AVERROR_EXTERNAL;
1287  }
1288 
1289  if (vtctx->prio_speed >= 0) {
1290  status = VTSessionSetProperty(vtctx->session,
1291  compat_keys.kVTCompressionPropertyKey_PrioritizeEncodingSpeedOverQuality,
1292  vtctx->prio_speed ? kCFBooleanTrue : kCFBooleanFalse);
1293  if (status) {
1294  av_log(avctx, AV_LOG_WARNING, "PrioritizeEncodingSpeedOverQuality property is not supported on this device. Ignoring.\n");
1295  }
1296  }
1297 
1298  if ((vtctx->codec_id == AV_CODEC_ID_H264 || vtctx->codec_id == AV_CODEC_ID_HEVC)
1299  && max_rate > 0) {
1300  bytes_per_second_value = max_rate >> 3;
1301  bytes_per_second = CFNumberCreate(kCFAllocatorDefault,
1302  kCFNumberSInt64Type,
1303  &bytes_per_second_value);
1304  if (!bytes_per_second) {
1305  return AVERROR(ENOMEM);
1306  }
1307  one_second_value = 1;
1308  one_second = CFNumberCreate(kCFAllocatorDefault,
1309  kCFNumberSInt64Type,
1310  &one_second_value);
1311  if (!one_second) {
1312  CFRelease(bytes_per_second);
1313  return AVERROR(ENOMEM);
1314  }
1315  nums[0] = (void *)bytes_per_second;
1316  nums[1] = (void *)one_second;
1317  data_rate_limits = CFArrayCreate(kCFAllocatorDefault,
1318  (const void **)nums,
1319  2,
1320  &kCFTypeArrayCallBacks);
1321 
1322  if (!data_rate_limits) {
1323  CFRelease(bytes_per_second);
1324  CFRelease(one_second);
1325  return AVERROR(ENOMEM);
1326  }
1327  status = VTSessionSetProperty(vtctx->session,
1328  kVTCompressionPropertyKey_DataRateLimits,
1329  data_rate_limits);
1330 
1331  CFRelease(bytes_per_second);
1332  CFRelease(one_second);
1333  CFRelease(data_rate_limits);
1334 
1335  if (status) {
1336  av_log(avctx, AV_LOG_ERROR, "Error setting max bitrate property: %d\n", status);
1337  // kVTCompressionPropertyKey_DataRateLimits is available for HEVC
1338  // now but not on old release. There is no document about since
1339  // when. So ignore the error if it failed for hevc.
1340  if (vtctx->codec_id != AV_CODEC_ID_HEVC)
1341  return AVERROR_EXTERNAL;
1342  }
1343  }
1344 
1345  if (vtctx->codec_id == AV_CODEC_ID_HEVC) {
1346  if (avctx->pix_fmt == AV_PIX_FMT_BGRA && vtctx->alpha_quality > 0.0) {
1347  CFNumberRef alpha_quality_num = CFNumberCreate(kCFAllocatorDefault,
1348  kCFNumberDoubleType,
1349  &vtctx->alpha_quality);
1350  if (!alpha_quality_num) return AVERROR(ENOMEM);
1351 
1352  status = VTSessionSetProperty(vtctx->session,
1353  compat_keys.kVTCompressionPropertyKey_TargetQualityForAlpha,
1354  alpha_quality_num);
1355  CFRelease(alpha_quality_num);
1356 
1357  if (status) {
1358  av_log(avctx,
1359  AV_LOG_ERROR,
1360  "Error setting alpha quality: %d\n",
1361  status);
1362  }
1363  }
1364  }
1365 
1366  if (profile_level) {
1367  status = VTSessionSetProperty(vtctx->session,
1368  kVTCompressionPropertyKey_ProfileLevel,
1369  profile_level);
1370  if (status) {
1371  av_log(avctx, AV_LOG_ERROR, "Error setting profile/level property: %d. Output will be encoded using a supported profile/level combination.\n", status);
1372  }
1373  }
1374 
1375  if (avctx->gop_size > 0 && avctx->codec_id != AV_CODEC_ID_PRORES) {
1376  CFNumberRef interval = CFNumberCreate(kCFAllocatorDefault,
1377  kCFNumberIntType,
1378  &avctx->gop_size);
1379  if (!interval) {
1380  return AVERROR(ENOMEM);
1381  }
1382 
1383  status = VTSessionSetProperty(vtctx->session,
1384  kVTCompressionPropertyKey_MaxKeyFrameInterval,
1385  interval);
1386  CFRelease(interval);
1387 
1388  if (status) {
1389  av_log(avctx, AV_LOG_ERROR, "Error setting 'max key-frame interval' property: %d\n", status);
1390  return AVERROR_EXTERNAL;
1391  }
1392  }
1393 
1394  if (vtctx->frames_before) {
1395  status = VTSessionSetProperty(vtctx->session,
1396  kVTCompressionPropertyKey_MoreFramesBeforeStart,
1397  kCFBooleanTrue);
1398 
1399  if (status == kVTPropertyNotSupportedErr) {
1400  av_log(avctx, AV_LOG_WARNING, "frames_before property is not supported on this device. Ignoring.\n");
1401  } else if (status) {
1402  av_log(avctx, AV_LOG_ERROR, "Error setting frames_before property: %d\n", status);
1403  }
1404  }
1405 
1406  if (vtctx->frames_after) {
1407  status = VTSessionSetProperty(vtctx->session,
1408  kVTCompressionPropertyKey_MoreFramesAfterEnd,
1409  kCFBooleanTrue);
1410 
1411  if (status == kVTPropertyNotSupportedErr) {
1412  av_log(avctx, AV_LOG_WARNING, "frames_after property is not supported on this device. Ignoring.\n");
1413  } else if (status) {
1414  av_log(avctx, AV_LOG_ERROR, "Error setting frames_after property: %d\n", status);
1415  }
1416  }
1417 
1418  if (avctx->sample_aspect_ratio.num != 0) {
1419  CFNumberRef num;
1420  CFNumberRef den;
1421  CFMutableDictionaryRef par;
1422  AVRational *avpar = &avctx->sample_aspect_ratio;
1423 
1424  av_reduce(&avpar->num, &avpar->den,
1425  avpar->num, avpar->den,
1426  0xFFFFFFFF);
1427 
1428  num = CFNumberCreate(kCFAllocatorDefault,
1429  kCFNumberIntType,
1430  &avpar->num);
1431 
1432  den = CFNumberCreate(kCFAllocatorDefault,
1433  kCFNumberIntType,
1434  &avpar->den);
1435 
1436 
1437 
1438  par = CFDictionaryCreateMutable(kCFAllocatorDefault,
1439  2,
1440  &kCFCopyStringDictionaryKeyCallBacks,
1441  &kCFTypeDictionaryValueCallBacks);
1442 
1443  if (!par || !num || !den) {
1444  if (par) CFRelease(par);
1445  if (num) CFRelease(num);
1446  if (den) CFRelease(den);
1447 
1448  return AVERROR(ENOMEM);
1449  }
1450 
1451  CFDictionarySetValue(
1452  par,
1453  kCMFormatDescriptionKey_PixelAspectRatioHorizontalSpacing,
1454  num);
1455 
1456  CFDictionarySetValue(
1457  par,
1458  kCMFormatDescriptionKey_PixelAspectRatioVerticalSpacing,
1459  den);
1460 
1461  status = VTSessionSetProperty(vtctx->session,
1462  kVTCompressionPropertyKey_PixelAspectRatio,
1463  par);
1464 
1465  CFRelease(par);
1466  CFRelease(num);
1467  CFRelease(den);
1468 
1469  if (status) {
1470  av_log(avctx,
1471  AV_LOG_ERROR,
1472  "Error setting pixel aspect ratio to %d:%d: %d.\n",
1473  avctx->sample_aspect_ratio.num,
1474  avctx->sample_aspect_ratio.den,
1475  status);
1476 
1477  return AVERROR_EXTERNAL;
1478  }
1479  }
1480 
1481 
1482  if (vtctx->transfer_function) {
1483  status = VTSessionSetProperty(vtctx->session,
1484  kVTCompressionPropertyKey_TransferFunction,
1485  vtctx->transfer_function);
1486 
1487  if (status) {
1488  av_log(avctx, AV_LOG_WARNING, "Could not set transfer function: %d\n", status);
1489  }
1490  }
1491 
1492 
1493  if (vtctx->ycbcr_matrix) {
1494  status = VTSessionSetProperty(vtctx->session,
1495  kVTCompressionPropertyKey_YCbCrMatrix,
1496  vtctx->ycbcr_matrix);
1497 
1498  if (status) {
1499  av_log(avctx, AV_LOG_WARNING, "Could not set ycbcr matrix: %d\n", status);
1500  }
1501  }
1502 
1503 
1504  if (vtctx->color_primaries) {
1505  status = VTSessionSetProperty(vtctx->session,
1506  kVTCompressionPropertyKey_ColorPrimaries,
1507  vtctx->color_primaries);
1508 
1509  if (status) {
1510  av_log(avctx, AV_LOG_WARNING, "Could not set color primaries: %d\n", status);
1511  }
1512  }
1513 
1514  if (gamma_level) {
1515  status = VTSessionSetProperty(vtctx->session,
1516  kCVImageBufferGammaLevelKey,
1517  gamma_level);
1518 
1519  if (status) {
1520  av_log(avctx, AV_LOG_WARNING, "Could not set gamma level: %d\n", status);
1521  }
1522  }
1523 
1524  if (!vtctx->has_b_frames && avctx->codec_id != AV_CODEC_ID_PRORES) {
1525  status = VTSessionSetProperty(vtctx->session,
1526  kVTCompressionPropertyKey_AllowFrameReordering,
1527  kCFBooleanFalse);
1528 
1529  if (status) {
1530  av_log(avctx, AV_LOG_ERROR, "Error setting 'allow frame reordering' property: %d\n", status);
1531  return AVERROR_EXTERNAL;
1532  }
1533  }
1534 
1535  if (vtctx->entropy != VT_ENTROPY_NOT_SET) {
1536  CFStringRef entropy = vtctx->entropy == VT_CABAC ?
1537  compat_keys.kVTH264EntropyMode_CABAC:
1538  compat_keys.kVTH264EntropyMode_CAVLC;
1539 
1540  status = VTSessionSetProperty(vtctx->session,
1541  compat_keys.kVTCompressionPropertyKey_H264EntropyMode,
1542  entropy);
1543 
1544  if (status) {
1545  av_log(avctx, AV_LOG_ERROR, "Error setting entropy property: %d\n", status);
1546  }
1547  }
1548 
1549  if (vtctx->realtime >= 0) {
1550  status = VTSessionSetProperty(vtctx->session,
1551  compat_keys.kVTCompressionPropertyKey_RealTime,
1552  vtctx->realtime ? kCFBooleanTrue : kCFBooleanFalse);
1553 
1554  if (status) {
1555  av_log(avctx, AV_LOG_ERROR, "Error setting realtime property: %d\n", status);
1556  }
1557  }
1558 
1559  if ((avctx->flags & AV_CODEC_FLAG_CLOSED_GOP) != 0) {
1561  compat_keys.kVTCompressionPropertyKey_AllowOpenGOP,
1562  "AllowOpenGop",
1563  kCFBooleanFalse);
1564  }
1565 
1566  if (avctx->qmin >= 0) {
1568  compat_keys.kVTCompressionPropertyKey_MinAllowedFrameQP,
1569  "qmin",
1570  avctx->qmin);
1571 
1572  if (status != 0) {
1573  return status;
1574  }
1575  }
1576 
1577  if (avctx->qmax >= 0) {
1579  compat_keys.kVTCompressionPropertyKey_MaxAllowedFrameQP,
1580  "qmax",
1581  avctx->qmax);
1582 
1583  if (status != 0) {
1584  return status;
1585  }
1586  }
1587 
1588  if (vtctx->max_slice_bytes >= 0 && avctx->codec_id == AV_CODEC_ID_H264) {
1590  kVTCompressionPropertyKey_MaxH264SliceBytes,
1591  "max_slice_bytes",
1592  vtctx->max_slice_bytes);
1593 
1594  if (status != 0) {
1595  return status;
1596  }
1597  }
1598 
1599  if (vtctx->power_efficient >= 0) {
1601  compat_keys.kVTCompressionPropertyKey_MaximizePowerEfficiency,
1602  "power_efficient",
1603  vtctx->power_efficient ? kCFBooleanTrue : kCFBooleanFalse);
1604  }
1605 
1606  if (vtctx->max_ref_frames > 0) {
1608  compat_keys.kVTCompressionPropertyKey_ReferenceBufferCount,
1609  "max_ref_frames",
1610  vtctx->max_ref_frames);
1611 
1612  if (status != 0) {
1613  return status;
1614  }
1615  }
1616 
1617  if (vtctx->spatialaq >= 0) {
1619  compat_keys.kVTCompressionPropertyKey_SpatialAdaptiveQPLevel,
1620  "spatialaq",
1622  }
1623 
1624  status = VTCompressionSessionPrepareToEncodeFrames(vtctx->session);
1625  if (status) {
1626  av_log(avctx, AV_LOG_ERROR, "Error: cannot prepare encoder: %d\n", status);
1627  return AVERROR_EXTERNAL;
1628  }
1629 
1630  return 0;
1631 }
1632 
1634 {
1635  CFMutableDictionaryRef enc_info;
1636  CFMutableDictionaryRef pixel_buffer_info = NULL;
1637  CMVideoCodecType codec_type;
1638  VTEncContext *vtctx = avctx->priv_data;
1639  CFStringRef profile_level = NULL;
1640  CFNumberRef gamma_level = NULL;
1641  int status;
1642 
1643  codec_type = get_cm_codec_type(avctx, vtctx->profile, vtctx->alpha_quality);
1644  if (!codec_type) {
1645  av_log(avctx, AV_LOG_ERROR, "Error: no mapping for AVCodecID %d\n", avctx->codec_id);
1646  return AVERROR(EINVAL);
1647  }
1648 
1649 #if defined(MAC_OS_X_VERSION_10_9) && !TARGET_OS_IPHONE && (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_9)
1650  if (avctx->codec_id == AV_CODEC_ID_PRORES) {
1651  if (__builtin_available(macOS 10.10, *)) {
1652  VTRegisterProfessionalVideoWorkflowVideoEncoders();
1653  }
1654  }
1655 #endif
1656 
1657  vtctx->codec_id = avctx->codec_id;
1658 
1659  if (vtctx->codec_id == AV_CODEC_ID_H264) {
1660  vtctx->get_param_set_func = CMVideoFormatDescriptionGetH264ParameterSetAtIndex;
1661 
1662  vtctx->has_b_frames = avctx->max_b_frames > 0;
1663  if(vtctx->has_b_frames && (0xFF & vtctx->profile) == AV_PROFILE_H264_BASELINE){
1664  av_log(avctx, AV_LOG_WARNING, "Cannot use B-frames with baseline profile. Output will not contain B-frames.\n");
1665  vtctx->has_b_frames = 0;
1666  }
1667 
1668  if (vtctx->entropy == VT_CABAC && (0xFF & vtctx->profile) == AV_PROFILE_H264_BASELINE) {
1669  av_log(avctx, AV_LOG_WARNING, "CABAC entropy requires 'main' or 'high' profile, but baseline was requested. Encode will not use CABAC entropy.\n");
1670  vtctx->entropy = VT_ENTROPY_NOT_SET;
1671  }
1672 
1673  if (!get_vt_h264_profile_level(avctx, &profile_level)) return AVERROR(EINVAL);
1674  } else if (vtctx->codec_id == AV_CODEC_ID_HEVC) {
1675  vtctx->get_param_set_func = compat_keys.CMVideoFormatDescriptionGetHEVCParameterSetAtIndex;
1676  if (!vtctx->get_param_set_func) return AVERROR(EINVAL);
1677  if (!get_vt_hevc_profile_level(avctx, &profile_level)) return AVERROR(EINVAL);
1678  // HEVC has b-byramid
1679  vtctx->has_b_frames = avctx->max_b_frames > 0 ? 2 : 0;
1680  } else if (vtctx->codec_id == AV_CODEC_ID_PRORES) {
1681  avctx->codec_tag = av_bswap32(codec_type);
1682  }
1683 
1684  enc_info = CFDictionaryCreateMutable(
1685  kCFAllocatorDefault,
1686  20,
1687  &kCFCopyStringDictionaryKeyCallBacks,
1688  &kCFTypeDictionaryValueCallBacks
1689  );
1690 
1691  if (!enc_info) return AVERROR(ENOMEM);
1692 
1693 #if !TARGET_OS_IPHONE
1694  if(vtctx->require_sw) {
1695  CFDictionarySetValue(enc_info,
1696  compat_keys.kVTVideoEncoderSpecification_EnableHardwareAcceleratedVideoEncoder,
1697  kCFBooleanFalse);
1698  } else if (!vtctx->allow_sw) {
1699  CFDictionarySetValue(enc_info,
1700  compat_keys.kVTVideoEncoderSpecification_RequireHardwareAcceleratedVideoEncoder,
1701  kCFBooleanTrue);
1702  } else {
1703  CFDictionarySetValue(enc_info,
1704  compat_keys.kVTVideoEncoderSpecification_EnableHardwareAcceleratedVideoEncoder,
1705  kCFBooleanTrue);
1706  }
1707 #endif
1708 
1709  // low-latency mode: eliminate frame reordering, follow a one-in-one-out encoding mode
1710  if ((avctx->flags & AV_CODEC_FLAG_LOW_DELAY) && avctx->codec_id == AV_CODEC_ID_H264) {
1711  CFDictionarySetValue(enc_info,
1712  compat_keys.kVTVideoEncoderSpecification_EnableLowLatencyRateControl,
1713  kCFBooleanTrue);
1714  }
1715 
1716  if (avctx->pix_fmt != AV_PIX_FMT_VIDEOTOOLBOX) {
1717  status = create_cv_pixel_buffer_info(avctx, &pixel_buffer_info);
1718  if (status)
1719  goto init_cleanup;
1720  }
1721 
1722  vtctx->dts_delta = vtctx->has_b_frames ? -1 : 0;
1723 
1724  get_cv_gamma(avctx, &gamma_level);
1728 
1729 
1730  if (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
1732  codec_type,
1733  profile_level,
1734  gamma_level,
1735  enc_info,
1736  pixel_buffer_info);
1737  if (status)
1738  goto init_cleanup;
1739  }
1740 
1741  status = vtenc_create_encoder(avctx,
1742  codec_type,
1743  profile_level,
1744  gamma_level,
1745  enc_info,
1746  pixel_buffer_info,
1747  vtctx->constant_bit_rate,
1748  &vtctx->session);
1749 
1750 init_cleanup:
1751  if (gamma_level)
1752  CFRelease(gamma_level);
1753 
1754  if (pixel_buffer_info)
1755  CFRelease(pixel_buffer_info);
1756 
1757  CFRelease(enc_info);
1758 
1759  return status;
1760 }
1761 
1763 {
1764  VTEncContext *vtctx = avctx->priv_data;
1765  CFBooleanRef has_b_frames_cfbool;
1766  int status;
1767 
1769 
1770  pthread_mutex_init(&vtctx->lock, NULL);
1772 
1773  // It can happen when user set avctx->profile directly.
1774  if (vtctx->profile == AV_PROFILE_UNKNOWN)
1775  vtctx->profile = avctx->profile;
1777  if (status) return status;
1778 
1779  status = VTSessionCopyProperty(vtctx->session,
1780  kVTCompressionPropertyKey_AllowFrameReordering,
1781  kCFAllocatorDefault,
1782  &has_b_frames_cfbool);
1783 
1784  if (!status && has_b_frames_cfbool) {
1785  //Some devices don't output B-frames for main profile, even if requested.
1786  // HEVC has b-pyramid
1787  if (CFBooleanGetValue(has_b_frames_cfbool))
1788  vtctx->has_b_frames = avctx->codec_id == AV_CODEC_ID_HEVC ? 2 : 1;
1789  else
1790  vtctx->has_b_frames = 0;
1791  CFRelease(has_b_frames_cfbool);
1792  }
1793  avctx->has_b_frames = vtctx->has_b_frames;
1794 
1795  return 0;
1796 }
1797 
1798 static void vtenc_get_frame_info(CMSampleBufferRef buffer, bool *is_key_frame)
1799 {
1800  CFArrayRef attachments;
1801  CFDictionaryRef attachment;
1802  CFBooleanRef not_sync;
1803  CFIndex len;
1804 
1805  attachments = CMSampleBufferGetSampleAttachmentsArray(buffer, false);
1806  len = !attachments ? 0 : CFArrayGetCount(attachments);
1807 
1808  if (!len) {
1809  *is_key_frame = true;
1810  return;
1811  }
1812 
1813  attachment = CFArrayGetValueAtIndex(attachments, 0);
1814 
1815  if (CFDictionaryGetValueIfPresent(attachment,
1816  kCMSampleAttachmentKey_NotSync,
1817  (const void **)&not_sync))
1818  {
1819  *is_key_frame = !CFBooleanGetValue(not_sync);
1820  } else {
1821  *is_key_frame = true;
1822  }
1823 }
1824 
1825 static int is_post_sei_nal_type(int nal_type){
1826  return nal_type != H264_NAL_SEI &&
1827  nal_type != H264_NAL_SPS &&
1828  nal_type != H264_NAL_PPS &&
1829  nal_type != H264_NAL_AUD;
1830 }
1831 
1832 /*
1833  * Finds the sei message start/size of type find_sei_type.
1834  * If more than one of that type exists, the last one is returned.
1835  */
1836 static int find_sei_end(AVCodecContext *avctx,
1837  uint8_t *nal_data,
1838  size_t nal_size,
1839  uint8_t **sei_end)
1840 {
1841  int nal_type;
1842  size_t sei_payload_size = 0;
1843  uint8_t *nal_start = nal_data;
1844  *sei_end = NULL;
1845 
1846  if (!nal_size)
1847  return 0;
1848 
1849  nal_type = *nal_data & 0x1F;
1850  if (nal_type != H264_NAL_SEI)
1851  return 0;
1852 
1853  nal_data++;
1854  nal_size--;
1855 
1856  if (nal_data[nal_size - 1] == 0x80)
1857  nal_size--;
1858 
1859  while (nal_size > 0 && *nal_data > 0) {
1860  do{
1861  nal_data++;
1862  nal_size--;
1863  } while (nal_size > 0 && *nal_data == 0xFF);
1864 
1865  if (!nal_size) {
1866  av_log(avctx, AV_LOG_ERROR, "Unexpected end of SEI NAL Unit parsing type.\n");
1867  return AVERROR_INVALIDDATA;
1868  }
1869 
1870  do{
1871  sei_payload_size += *nal_data;
1872  nal_data++;
1873  nal_size--;
1874  } while (nal_size > 0 && *nal_data == 0xFF);
1875 
1876  if (nal_size < sei_payload_size) {
1877  av_log(avctx, AV_LOG_ERROR, "Unexpected end of SEI NAL Unit parsing size.\n");
1878  return AVERROR_INVALIDDATA;
1879  }
1880 
1881  nal_data += sei_payload_size;
1882  nal_size -= sei_payload_size;
1883  }
1884 
1885  *sei_end = nal_data;
1886 
1887  return nal_data - nal_start + 1;
1888 }
1889 
1890 /**
1891  * Copies the data inserting emulation prevention bytes as needed.
1892  * Existing data in the destination can be taken into account by providing
1893  * dst with a dst_offset > 0.
1894  *
1895  * @return The number of bytes copied on success. On failure, the negative of
1896  * the number of bytes needed to copy src is returned.
1897  */
1898 static int copy_emulation_prev(const uint8_t *src,
1899  size_t src_size,
1900  uint8_t *dst,
1901  ssize_t dst_offset,
1902  size_t dst_size)
1903 {
1904  int zeros = 0;
1905  int wrote_bytes;
1906  uint8_t* dst_start;
1907  uint8_t* dst_end = dst + dst_size;
1908  const uint8_t* src_end = src + src_size;
1909  int start_at = dst_offset > 2 ? dst_offset - 2 : 0;
1910  int i;
1911  for (i = start_at; i < dst_offset && i < dst_size; i++) {
1912  if (!dst[i])
1913  zeros++;
1914  else
1915  zeros = 0;
1916  }
1917 
1918  dst += dst_offset;
1919  dst_start = dst;
1920  for (; src < src_end; src++, dst++) {
1921  if (zeros == 2) {
1922  int insert_ep3_byte = *src <= 3;
1923  if (insert_ep3_byte) {
1924  if (dst < dst_end)
1925  *dst = 3;
1926  dst++;
1927  }
1928 
1929  zeros = 0;
1930  }
1931 
1932  if (dst < dst_end)
1933  *dst = *src;
1934 
1935  if (!*src)
1936  zeros++;
1937  else
1938  zeros = 0;
1939  }
1940 
1941  wrote_bytes = dst - dst_start;
1942 
1943  if (dst > dst_end)
1944  return -wrote_bytes;
1945 
1946  return wrote_bytes;
1947 }
1948 
1949 static int write_sei(const ExtraSEI *sei,
1950  int sei_type,
1951  uint8_t *dst,
1952  size_t dst_size)
1953 {
1954  uint8_t *sei_start = dst;
1955  size_t remaining_sei_size = sei->size;
1956  size_t remaining_dst_size = dst_size;
1957  int header_bytes;
1958  int bytes_written;
1959  ssize_t offset;
1960 
1961  if (!remaining_dst_size)
1962  return AVERROR_BUFFER_TOO_SMALL;
1963 
1964  while (sei_type && remaining_dst_size != 0) {
1965  int sei_byte = sei_type > 255 ? 255 : sei_type;
1966  *dst = sei_byte;
1967 
1968  sei_type -= sei_byte;
1969  dst++;
1970  remaining_dst_size--;
1971  }
1972 
1973  if (!dst_size)
1974  return AVERROR_BUFFER_TOO_SMALL;
1975 
1976  while (remaining_sei_size && remaining_dst_size != 0) {
1977  int size_byte = remaining_sei_size > 255 ? 255 : remaining_sei_size;
1978  *dst = size_byte;
1979 
1980  remaining_sei_size -= size_byte;
1981  dst++;
1982  remaining_dst_size--;
1983  }
1984 
1985  if (remaining_dst_size < sei->size)
1986  return AVERROR_BUFFER_TOO_SMALL;
1987 
1988  header_bytes = dst - sei_start;
1989 
1990  offset = header_bytes;
1991  bytes_written = copy_emulation_prev(sei->data,
1992  sei->size,
1993  sei_start,
1994  offset,
1995  dst_size);
1996  if (bytes_written < 0)
1997  return AVERROR_BUFFER_TOO_SMALL;
1998 
1999  bytes_written += header_bytes;
2000  return bytes_written;
2001 }
2002 
2003 /**
2004  * Copies NAL units and replaces length codes with
2005  * H.264 Annex B start codes. On failure, the contents of
2006  * dst_data may have been modified.
2007  *
2008  * @param length_code_size Byte length of each length code
2009  * @param sample_buffer NAL units prefixed with length codes.
2010  * @param sei Optional A53 closed captions SEI data.
2011  * @param dst_data Must be zeroed before calling this function.
2012  * Contains the copied NAL units prefixed with
2013  * start codes when the function returns
2014  * successfully.
2015  * @param dst_size Length of dst_data
2016  * @return 0 on success
2017  * AVERROR_INVALIDDATA if length_code_size is invalid
2018  * AVERROR_BUFFER_TOO_SMALL if dst_data is too small
2019  * or if a length_code in src_data specifies data beyond
2020  * the end of its buffer.
2021  */
2023  AVCodecContext *avctx,
2024  size_t length_code_size,
2025  CMSampleBufferRef sample_buffer,
2026  ExtraSEI *sei,
2027  uint8_t *dst_data,
2028  size_t dst_size)
2029 {
2030  size_t src_size = CMSampleBufferGetTotalSampleSize(sample_buffer);
2031  size_t remaining_src_size = src_size;
2032  size_t remaining_dst_size = dst_size;
2033  size_t src_offset = 0;
2034  int wrote_sei = 0;
2035  int status;
2036  uint8_t size_buf[4];
2037  uint8_t nal_type;
2038  CMBlockBufferRef block = CMSampleBufferGetDataBuffer(sample_buffer);
2039 
2040  if (length_code_size > 4) {
2041  return AVERROR_INVALIDDATA;
2042  }
2043 
2044  while (remaining_src_size > 0) {
2045  size_t curr_src_len;
2046  size_t curr_dst_len;
2047  size_t box_len = 0;
2048  size_t i;
2049 
2050  uint8_t *dst_box;
2051 
2052  status = CMBlockBufferCopyDataBytes(block,
2053  src_offset,
2054  length_code_size,
2055  size_buf);
2056  if (status) {
2057  av_log(avctx, AV_LOG_ERROR, "Cannot copy length: %d\n", status);
2058  return AVERROR_EXTERNAL;
2059  }
2060 
2061  status = CMBlockBufferCopyDataBytes(block,
2062  src_offset + length_code_size,
2063  1,
2064  &nal_type);
2065 
2066  if (status) {
2067  av_log(avctx, AV_LOG_ERROR, "Cannot copy type: %d\n", status);
2068  return AVERROR_EXTERNAL;
2069  }
2070 
2071  nal_type &= 0x1F;
2072 
2073  for (i = 0; i < length_code_size; i++) {
2074  box_len <<= 8;
2075  box_len |= size_buf[i];
2076  }
2077 
2078  if (sei && !wrote_sei && is_post_sei_nal_type(nal_type)) {
2079  //No SEI NAL unit - insert.
2080  int wrote_bytes;
2081 
2082  memcpy(dst_data, start_code, sizeof(start_code));
2083  dst_data += sizeof(start_code);
2084  remaining_dst_size -= sizeof(start_code);
2085 
2086  *dst_data = H264_NAL_SEI;
2087  dst_data++;
2088  remaining_dst_size--;
2089 
2090  wrote_bytes = write_sei(sei,
2092  dst_data,
2093  remaining_dst_size);
2094 
2095  if (wrote_bytes < 0)
2096  return wrote_bytes;
2097 
2098  remaining_dst_size -= wrote_bytes;
2099  dst_data += wrote_bytes;
2100 
2101  if (remaining_dst_size <= 0)
2102  return AVERROR_BUFFER_TOO_SMALL;
2103 
2104  *dst_data = 0x80;
2105 
2106  dst_data++;
2107  remaining_dst_size--;
2108 
2109  wrote_sei = 1;
2110  }
2111 
2112  curr_src_len = box_len + length_code_size;
2113  curr_dst_len = box_len + sizeof(start_code);
2114 
2115  if (remaining_src_size < curr_src_len) {
2116  return AVERROR_BUFFER_TOO_SMALL;
2117  }
2118 
2119  if (remaining_dst_size < curr_dst_len) {
2120  return AVERROR_BUFFER_TOO_SMALL;
2121  }
2122 
2123  dst_box = dst_data + sizeof(start_code);
2124 
2125  memcpy(dst_data, start_code, sizeof(start_code));
2126  status = CMBlockBufferCopyDataBytes(block,
2127  src_offset + length_code_size,
2128  box_len,
2129  dst_box);
2130 
2131  if (status) {
2132  av_log(avctx, AV_LOG_ERROR, "Cannot copy data: %d\n", status);
2133  return AVERROR_EXTERNAL;
2134  }
2135 
2136  if (sei && !wrote_sei && nal_type == H264_NAL_SEI) {
2137  //Found SEI NAL unit - append.
2138  int wrote_bytes;
2139  int old_sei_length;
2140  int extra_bytes;
2141  uint8_t *new_sei;
2142  old_sei_length = find_sei_end(avctx, dst_box, box_len, &new_sei);
2143  if (old_sei_length < 0)
2144  return status;
2145 
2146  wrote_bytes = write_sei(sei,
2148  new_sei,
2149  remaining_dst_size - old_sei_length);
2150  if (wrote_bytes < 0)
2151  return wrote_bytes;
2152 
2153  if (new_sei + wrote_bytes >= dst_data + remaining_dst_size)
2154  return AVERROR_BUFFER_TOO_SMALL;
2155 
2156  new_sei[wrote_bytes++] = 0x80;
2157  extra_bytes = wrote_bytes - (dst_box + box_len - new_sei);
2158 
2159  dst_data += extra_bytes;
2160  remaining_dst_size -= extra_bytes;
2161 
2162  wrote_sei = 1;
2163  }
2164 
2165  src_offset += curr_src_len;
2166  dst_data += curr_dst_len;
2167 
2168  remaining_src_size -= curr_src_len;
2169  remaining_dst_size -= curr_dst_len;
2170  }
2171 
2172  return 0;
2173 }
2174 
2175 /**
2176  * Returns a sufficient number of bytes to contain the sei data.
2177  * It may be greater than the minimum required.
2178  */
2179 static int get_sei_msg_bytes(const ExtraSEI* sei, int type){
2180  int copied_size;
2181  if (sei->size == 0)
2182  return 0;
2183 
2184  copied_size = -copy_emulation_prev(sei->data,
2185  sei->size,
2186  NULL,
2187  0,
2188  0);
2189 
2190  if ((sei->size % 255) == 0) //may result in an extra byte
2191  copied_size++;
2192 
2193  return copied_size + sei->size / 255 + 1 + type / 255 + 1;
2194 }
2195 
2197  AVCodecContext *avctx,
2198  CMSampleBufferRef sample_buffer,
2199  AVPacket *pkt,
2200  ExtraSEI *sei)
2201 {
2202  VTEncContext *vtctx = avctx->priv_data;
2203 
2204  int status;
2205  bool is_key_frame;
2206  bool add_header;
2207  size_t length_code_size;
2208  size_t header_size = 0;
2209  size_t in_buf_size;
2210  size_t out_buf_size;
2211  size_t sei_nalu_size = 0;
2212  int64_t dts_delta;
2213  int64_t time_base_num;
2214  int nalu_count;
2215  CMTime pts;
2216  CMTime dts;
2217  CMVideoFormatDescriptionRef vid_fmt;
2218 
2219  vtenc_get_frame_info(sample_buffer, &is_key_frame);
2220 
2221  if (vtctx->get_param_set_func) {
2222  status = get_length_code_size(avctx, sample_buffer, &length_code_size);
2223  if (status) return status;
2224 
2225  add_header = is_key_frame && !(avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER);
2226 
2227  if (add_header) {
2228  vid_fmt = CMSampleBufferGetFormatDescription(sample_buffer);
2229  if (!vid_fmt) {
2230  av_log(avctx, AV_LOG_ERROR, "Cannot get format description.\n");
2231  return AVERROR_EXTERNAL;
2232  }
2233 
2234  status = get_params_size(avctx, vid_fmt, &header_size);
2235  if (status) return status;
2236  }
2237 
2238  status = count_nalus(length_code_size, sample_buffer, &nalu_count);
2239  if(status)
2240  return status;
2241 
2242  if (sei) {
2243  size_t msg_size = get_sei_msg_bytes(sei,
2245 
2246  sei_nalu_size = sizeof(start_code) + 1 + msg_size + 1;
2247  }
2248 
2249  in_buf_size = CMSampleBufferGetTotalSampleSize(sample_buffer);
2250  out_buf_size = header_size +
2251  in_buf_size +
2252  sei_nalu_size +
2253  nalu_count * ((int)sizeof(start_code) - (int)length_code_size);
2254 
2255  status = ff_get_encode_buffer(avctx, pkt, out_buf_size, 0);
2256  if (status < 0)
2257  return status;
2258 
2259  if (add_header) {
2260  status = copy_param_sets(avctx, vid_fmt, pkt->data, out_buf_size);
2261  if(status) return status;
2262  }
2263 
2265  avctx,
2266  length_code_size,
2267  sample_buffer,
2268  sei,
2269  pkt->data + header_size,
2270  pkt->size - header_size
2271  );
2272 
2273  if (status) {
2274  av_log(avctx, AV_LOG_ERROR, "Error copying packet data: %d\n", status);
2275  return status;
2276  }
2277  } else {
2278  size_t len;
2279  CMBlockBufferRef buf = CMSampleBufferGetDataBuffer(sample_buffer);
2280  if (!buf) {
2281  av_log(avctx, AV_LOG_ERROR, "Error getting block buffer\n");
2282  return AVERROR_EXTERNAL;
2283  }
2284 
2285  len = CMBlockBufferGetDataLength(buf);
2286 
2287  status = ff_get_encode_buffer(avctx, pkt, len, 0);
2288  if (status < 0)
2289  return status;
2290 
2291  status = CMBlockBufferCopyDataBytes(buf, 0, len, pkt->data);
2292  if (status) {
2293  av_log(avctx, AV_LOG_ERROR, "Error copying packet data: %d\n", status);
2294  return AVERROR_EXTERNAL;
2295  }
2296  }
2297 
2298  if (is_key_frame) {
2300  }
2301 
2302  pts = CMSampleBufferGetPresentationTimeStamp(sample_buffer);
2303  dts = CMSampleBufferGetDecodeTimeStamp (sample_buffer);
2304 
2305  if (CMTIME_IS_INVALID(dts)) {
2306  if (!vtctx->has_b_frames) {
2307  dts = pts;
2308  } else {
2309  av_log(avctx, AV_LOG_ERROR, "DTS is invalid.\n");
2310  return AVERROR_EXTERNAL;
2311  }
2312  }
2313 
2314  dts_delta = vtctx->dts_delta >= 0 ? vtctx->dts_delta : 0;
2315  time_base_num = avctx->time_base.num;
2316  pkt->pts = pts.value / time_base_num;
2317  pkt->dts = dts.value / time_base_num - dts_delta;
2318 
2319  return 0;
2320 }
2321 
2322 /*
2323  * contiguous_buf_size is 0 if not contiguous, and the size of the buffer
2324  * containing all planes if so.
2325  */
2327  AVCodecContext *avctx,
2328  const AVFrame *frame,
2329  int *color,
2330  int *plane_count,
2331  size_t *widths,
2332  size_t *heights,
2333  size_t *strides,
2334  size_t *contiguous_buf_size)
2335 {
2337  VTEncContext *vtctx = avctx->priv_data;
2338  int av_format = frame->format;
2339  int av_color_range = avctx->color_range;
2340  int i;
2341  int range_guessed;
2342  int status;
2343 
2344  if (!desc)
2345  return AVERROR(EINVAL);
2346 
2347  status = get_cv_pixel_format(avctx, av_format, av_color_range, color, &range_guessed);
2348  if (status)
2349  return status;
2350 
2351  if (range_guessed) {
2352  if (!vtctx->warned_color_range) {
2353  vtctx->warned_color_range = true;
2354  av_log(avctx,
2356  "Color range not set for %s. Using MPEG range.\n",
2357  av_get_pix_fmt_name(av_format));
2358  }
2359  }
2360 
2361  *plane_count = av_pix_fmt_count_planes(avctx->pix_fmt);
2362 
2363  for (i = 0; i < desc->nb_components; i++) {
2364  int p = desc->comp[i].plane;
2365  bool hasAlpha = (desc->flags & AV_PIX_FMT_FLAG_ALPHA);
2366  bool isAlpha = hasAlpha && (p + 1 == *plane_count);
2367  bool isChroma = (p != 0) && !isAlpha;
2368  int shiftw = isChroma ? desc->log2_chroma_w : 0;
2369  int shifth = isChroma ? desc->log2_chroma_h : 0;
2370  widths[p] = (avctx->width + ((1 << shiftw) >> 1)) >> shiftw;
2371  heights[p] = (avctx->height + ((1 << shifth) >> 1)) >> shifth;
2372  strides[p] = frame->linesize[p];
2373  }
2374 
2375  *contiguous_buf_size = 0;
2376  for (i = 0; i < *plane_count; i++) {
2377  if (i < *plane_count - 1 &&
2378  frame->data[i] + strides[i] * heights[i] != frame->data[i + 1]) {
2379  *contiguous_buf_size = 0;
2380  break;
2381  }
2382 
2383  *contiguous_buf_size += strides[i] * heights[i];
2384  }
2385 
2386  return 0;
2387 }
2388 
2389 //Not used on OSX - frame is never copied.
2391  const AVFrame *frame,
2392  CVPixelBufferRef cv_img,
2393  const size_t *plane_strides,
2394  const size_t *plane_rows)
2395 {
2396  int i, j;
2397  size_t plane_count;
2398  int status;
2399  int rows;
2400  int src_stride;
2401  int dst_stride;
2402  uint8_t *src_addr;
2403  uint8_t *dst_addr;
2404  size_t copy_bytes;
2405 
2406  status = CVPixelBufferLockBaseAddress(cv_img, 0);
2407  if (status) {
2408  av_log(
2409  avctx,
2410  AV_LOG_ERROR,
2411  "Error: Could not lock base address of CVPixelBuffer: %d.\n",
2412  status
2413  );
2414  }
2415 
2416  if (CVPixelBufferIsPlanar(cv_img)) {
2417  plane_count = CVPixelBufferGetPlaneCount(cv_img);
2418  for (i = 0; frame->data[i]; i++) {
2419  if (i == plane_count) {
2420  CVPixelBufferUnlockBaseAddress(cv_img, 0);
2421  av_log(avctx,
2422  AV_LOG_ERROR,
2423  "Error: different number of planes in AVFrame and CVPixelBuffer.\n"
2424  );
2425 
2426  return AVERROR_EXTERNAL;
2427  }
2428 
2429  dst_addr = (uint8_t*)CVPixelBufferGetBaseAddressOfPlane(cv_img, i);
2430  src_addr = (uint8_t*)frame->data[i];
2431  dst_stride = CVPixelBufferGetBytesPerRowOfPlane(cv_img, i);
2432  src_stride = plane_strides[i];
2433  rows = plane_rows[i];
2434 
2435  if (dst_stride == src_stride) {
2436  memcpy(dst_addr, src_addr, src_stride * rows);
2437  } else {
2438  copy_bytes = dst_stride < src_stride ? dst_stride : src_stride;
2439 
2440  for (j = 0; j < rows; j++) {
2441  memcpy(dst_addr + j * dst_stride, src_addr + j * src_stride, copy_bytes);
2442  }
2443  }
2444  }
2445  } else {
2446  if (frame->data[1]) {
2447  CVPixelBufferUnlockBaseAddress(cv_img, 0);
2448  av_log(avctx,
2449  AV_LOG_ERROR,
2450  "Error: different number of planes in AVFrame and non-planar CVPixelBuffer.\n"
2451  );
2452 
2453  return AVERROR_EXTERNAL;
2454  }
2455 
2456  dst_addr = (uint8_t*)CVPixelBufferGetBaseAddress(cv_img);
2457  src_addr = (uint8_t*)frame->data[0];
2458  dst_stride = CVPixelBufferGetBytesPerRow(cv_img);
2459  src_stride = plane_strides[0];
2460  rows = plane_rows[0];
2461 
2462  if (dst_stride == src_stride) {
2463  memcpy(dst_addr, src_addr, src_stride * rows);
2464  } else {
2465  copy_bytes = dst_stride < src_stride ? dst_stride : src_stride;
2466 
2467  for (j = 0; j < rows; j++) {
2468  memcpy(dst_addr + j * dst_stride, src_addr + j * src_stride, copy_bytes);
2469  }
2470  }
2471  }
2472 
2473  status = CVPixelBufferUnlockBaseAddress(cv_img, 0);
2474  if (status) {
2475  av_log(avctx, AV_LOG_ERROR, "Error: Could not unlock CVPixelBuffer base address: %d.\n", status);
2476  return AVERROR_EXTERNAL;
2477  }
2478 
2479  return 0;
2480 }
2481 
2483  const AVFrame *frame,
2484  CVPixelBufferRef *cv_img,
2485  BufNode *node)
2486 {
2487  int plane_count;
2488  int color;
2489  size_t widths [AV_NUM_DATA_POINTERS];
2490  size_t heights[AV_NUM_DATA_POINTERS];
2491  size_t strides[AV_NUM_DATA_POINTERS];
2492  int status;
2493  size_t contiguous_buf_size;
2494  CVPixelBufferPoolRef pix_buf_pool;
2495  VTEncContext* vtctx = avctx->priv_data;
2496 
2497  if (avctx->pix_fmt == AV_PIX_FMT_VIDEOTOOLBOX) {
2499 
2500  *cv_img = (CVPixelBufferRef)frame->data[3];
2501  av_assert0(*cv_img);
2502 
2503  CFRetain(*cv_img);
2504  if (frame->buf[0]) {
2505  node->frame_buf = av_buffer_ref(frame->buf[0]);
2506  if (!node->frame_buf)
2507  return AVERROR(ENOMEM);
2508  }
2509 
2510  return 0;
2511  }
2512 
2513  memset(widths, 0, sizeof(widths));
2514  memset(heights, 0, sizeof(heights));
2515  memset(strides, 0, sizeof(strides));
2516 
2518  avctx,
2519  frame,
2520  &color,
2521  &plane_count,
2522  widths,
2523  heights,
2524  strides,
2525  &contiguous_buf_size
2526  );
2527 
2528  if (status) {
2529  av_log(
2530  avctx,
2531  AV_LOG_ERROR,
2532  "Error: Cannot convert format %d color_range %d: %d\n",
2533  frame->format,
2534  frame->color_range,
2535  status
2536  );
2537 
2538  return status;
2539  }
2540 
2541  pix_buf_pool = VTCompressionSessionGetPixelBufferPool(vtctx->session);
2542  if (!pix_buf_pool) {
2543  /* On iOS, the VT session is invalidated when the APP switches from
2544  * foreground to background and vice versa. Fetch the actual error code
2545  * of the VT session to detect that case and restart the VT session
2546  * accordingly. */
2547  OSStatus vtstatus;
2548 
2549  vtstatus = VTCompressionSessionPrepareToEncodeFrames(vtctx->session);
2550  if (vtstatus == kVTInvalidSessionErr) {
2551  vtenc_reset(vtctx);
2552 
2554  if (status == 0)
2555  pix_buf_pool = VTCompressionSessionGetPixelBufferPool(vtctx->session);
2556  }
2557  if (!pix_buf_pool) {
2558  av_log(avctx, AV_LOG_ERROR, "Could not get pixel buffer pool.\n");
2559  return AVERROR_EXTERNAL;
2560  }
2561  else
2562  av_log(avctx, AV_LOG_WARNING, "VT session restarted because of a "
2563  "kVTInvalidSessionErr error.\n");
2564  }
2565 
2566  status = CVPixelBufferPoolCreatePixelBuffer(NULL,
2567  pix_buf_pool,
2568  cv_img);
2569 
2570 
2571  if (status) {
2572  av_log(avctx, AV_LOG_ERROR, "Could not create pixel buffer from pool: %d.\n", status);
2573  return AVERROR_EXTERNAL;
2574  }
2575 
2576  status = copy_avframe_to_pixel_buffer(avctx, frame, *cv_img, strides, heights);
2577  if (status) {
2578  CFRelease(*cv_img);
2579  *cv_img = NULL;
2580  return status;
2581  }
2582 
2583  return 0;
2584 }
2585 
2587  CFDictionaryRef* dict_out)
2588 {
2589  CFDictionaryRef dict = NULL;
2590  if (frame->pict_type == AV_PICTURE_TYPE_I) {
2591  const void *keys[] = { kVTEncodeFrameOptionKey_ForceKeyFrame };
2592  const void *vals[] = { kCFBooleanTrue };
2593 
2594  dict = CFDictionaryCreate(NULL, keys, vals, 1, NULL, NULL);
2595  if(!dict) return AVERROR(ENOMEM);
2596  }
2597 
2598  *dict_out = dict;
2599  return 0;
2600 }
2601 
2603  VTEncContext *vtctx,
2604  const AVFrame *frame)
2605 {
2606  CMTime time;
2607  CFDictionaryRef frame_dict = NULL;
2608  CVPixelBufferRef cv_img = NULL;
2609  AVFrameSideData *side_data = NULL;
2610  BufNode *node = av_mallocz(sizeof(*node));
2611  int status;
2612 
2613  if (!node)
2614  return AVERROR(ENOMEM);
2615 
2616  status = create_cv_pixel_buffer(avctx, frame, &cv_img, node);
2617  if (status)
2618  goto out;
2619 
2620  status = create_encoder_dict_h264(frame, &frame_dict);
2621  if (status)
2622  goto out;
2623 
2624 #if CONFIG_ATSC_A53
2626  if (vtctx->a53_cc && side_data && side_data->size) {
2627  status = ff_alloc_a53_sei(frame, 0, &node->sei.data, &node->sei.size);
2628  if (status < 0) {
2629  goto out;
2630  }
2631  }
2632 #endif
2633 
2634  time = CMTimeMake(frame->pts * avctx->time_base.num, avctx->time_base.den);
2635  status = VTCompressionSessionEncodeFrame(
2636  vtctx->session,
2637  cv_img,
2638  time,
2639  kCMTimeInvalid,
2640  frame_dict,
2641  node,
2642  NULL
2643  );
2644 
2645  if (status) {
2646  av_log(avctx, AV_LOG_ERROR, "Error: cannot encode frame: %d\n", status);
2648  // Not necessary, just in case new code put after here
2649  goto out;
2650  }
2651 
2652 out:
2653  if (frame_dict)
2654  CFRelease(frame_dict);
2655  if (cv_img)
2656  CFRelease(cv_img);
2657  if (status)
2658  vtenc_free_buf_node(node);
2659 
2660  return status;
2661 }
2662 
2664  AVCodecContext *avctx,
2665  AVPacket *pkt,
2666  const AVFrame *frame,
2667  int *got_packet)
2668 {
2669  VTEncContext *vtctx = avctx->priv_data;
2670  bool get_frame;
2671  int status;
2672  CMSampleBufferRef buf = NULL;
2673  ExtraSEI sei = {0};
2674 
2675  if (frame) {
2676  status = vtenc_send_frame(avctx, vtctx, frame);
2677 
2678  if (status) {
2680  goto end_nopkt;
2681  }
2682 
2683  if (vtctx->frame_ct_in == 0) {
2684  vtctx->first_pts = frame->pts;
2685  } else if(vtctx->frame_ct_in == vtctx->has_b_frames) {
2686  vtctx->dts_delta = frame->pts - vtctx->first_pts;
2687  }
2688 
2689  vtctx->frame_ct_in++;
2690  } else if(!vtctx->flushing) {
2691  vtctx->flushing = true;
2692 
2693  status = VTCompressionSessionCompleteFrames(vtctx->session,
2694  kCMTimeIndefinite);
2695 
2696  if (status) {
2697  av_log(avctx, AV_LOG_ERROR, "Error flushing frames: %d\n", status);
2699  goto end_nopkt;
2700  }
2701  }
2702 
2703  *got_packet = 0;
2704  get_frame = vtctx->dts_delta >= 0 || !frame;
2705  if (!get_frame) {
2706  status = 0;
2707  goto end_nopkt;
2708  }
2709 
2710  status = vtenc_q_pop(vtctx, !frame, &buf, &sei);
2711  if (status) goto end_nopkt;
2712  if (!buf) goto end_nopkt;
2713 
2714  status = vtenc_cm_to_avpacket(avctx, buf, pkt, sei.data ? &sei : NULL);
2715  av_free(sei.data);
2716  CFRelease(buf);
2717  if (status) goto end_nopkt;
2718 
2719  *got_packet = 1;
2720  return 0;
2721 
2722 end_nopkt:
2724  return status;
2725 }
2726 
2728  CMVideoCodecType codec_type,
2729  CFStringRef profile_level,
2730  CFNumberRef gamma_level,
2731  CFDictionaryRef enc_info,
2732  CFDictionaryRef pixel_buffer_info)
2733 {
2734  VTEncContext *vtctx = avctx->priv_data;
2735  int status;
2736  CVPixelBufferPoolRef pool = NULL;
2737  CVPixelBufferRef pix_buf = NULL;
2738  CMTime time;
2739  CMSampleBufferRef buf = NULL;
2740  BufNode *node = av_mallocz(sizeof(*node));
2741 
2742  if (!node)
2743  return AVERROR(ENOMEM);
2744 
2745  status = vtenc_create_encoder(avctx,
2746  codec_type,
2747  profile_level,
2748  gamma_level,
2749  enc_info,
2750  pixel_buffer_info,
2751  vtctx->constant_bit_rate,
2752  &vtctx->session);
2753  if (status)
2754  goto pe_cleanup;
2755 
2756  pool = VTCompressionSessionGetPixelBufferPool(vtctx->session);
2757  if(!pool){
2758  av_log(avctx, AV_LOG_ERROR, "Error getting pixel buffer pool.\n");
2760  goto pe_cleanup;
2761  }
2762 
2763  status = CVPixelBufferPoolCreatePixelBuffer(NULL,
2764  pool,
2765  &pix_buf);
2766 
2767  if(status != kCVReturnSuccess){
2768  av_log(avctx, AV_LOG_ERROR, "Error creating frame from pool: %d\n", status);
2770  goto pe_cleanup;
2771  }
2772 
2773  time = CMTimeMake(0, avctx->time_base.den);
2774  status = VTCompressionSessionEncodeFrame(vtctx->session,
2775  pix_buf,
2776  time,
2777  kCMTimeInvalid,
2778  NULL,
2779  node,
2780  NULL);
2781 
2782  if (status) {
2783  av_log(avctx,
2784  AV_LOG_ERROR,
2785  "Error sending frame for extradata: %d\n",
2786  status);
2788  goto pe_cleanup;
2789  }
2790  node = NULL;
2791 
2792  //Populates extradata - output frames are flushed and param sets are available.
2793  status = VTCompressionSessionCompleteFrames(vtctx->session,
2794  kCMTimeIndefinite);
2795 
2796  if (status) {
2798  goto pe_cleanup;
2799  }
2800 
2801  status = vtenc_q_pop(vtctx, 0, &buf, NULL);
2802  if (status) {
2803  av_log(avctx, AV_LOG_ERROR, "popping: %d\n", status);
2804  goto pe_cleanup;
2805  }
2806 
2807  CFRelease(buf);
2808 
2809 
2810 
2811 pe_cleanup:
2812  CVPixelBufferRelease(pix_buf);
2813 
2814  if (status) {
2815  vtenc_reset(vtctx);
2816  } else if (vtctx->session) {
2817  CFRelease(vtctx->session);
2818  vtctx->session = NULL;
2819  }
2820 
2821  vtctx->frame_ct_out = 0;
2822 
2823  av_assert0(status != 0 || (avctx->extradata && avctx->extradata_size > 0));
2824  if (!status)
2825  vtenc_free_buf_node(node);
2826 
2827  return status;
2828 }
2829 
2831 {
2832  VTEncContext *vtctx = avctx->priv_data;
2833 
2834  if(!vtctx->session) {
2836  pthread_mutex_destroy(&vtctx->lock);
2837  return 0;
2838  }
2839 
2840  VTCompressionSessionCompleteFrames(vtctx->session,
2841  kCMTimeIndefinite);
2842  clear_frame_queue(vtctx);
2844  pthread_mutex_destroy(&vtctx->lock);
2845 
2846  vtenc_reset(vtctx);
2847 
2848  return 0;
2849 }
2850 
2851 static const enum AVPixelFormat avc_pix_fmts[] = {
2856 };
2857 
2858 static const enum AVPixelFormat hevc_pix_fmts[] = {
2866 };
2867 
2868 static const enum AVPixelFormat prores_pix_fmts[] = {
2871 #ifdef kCFCoreFoundationVersionNumber10_7
2874 #endif
2876 #if HAVE_KCVPIXELFORMATTYPE_420YPCBCR10BIPLANARVIDEORANGE
2878 #endif
2879 #if HAVE_KCVPIXELFORMATTYPE_422YPCBCR8BIPLANARVIDEORANGE
2881 #endif
2882 #if HAVE_KCVPIXELFORMATTYPE_422YPCBCR10BIPLANARVIDEORANGE
2884 #endif
2885 #if HAVE_KCVPIXELFORMATTYPE_422YPCBCR16BIPLANARVIDEORANGE
2887 #endif
2888 #if HAVE_KCVPIXELFORMATTYPE_444YPCBCR8BIPLANARVIDEORANGE
2890 #endif
2891 #if HAVE_KCVPIXELFORMATTYPE_444YPCBCR10BIPLANARVIDEORANGE
2893 #endif
2894 #if HAVE_KCVPIXELFORMATTYPE_444YPCBCR16BIPLANARVIDEORANGE
2896 #endif
2899 };
2900 
2901 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
2902 #define COMMON_OPTIONS \
2903  { "allow_sw", "Allow software encoding", OFFSET(allow_sw), AV_OPT_TYPE_BOOL, \
2904  { .i64 = 0 }, 0, 1, VE }, \
2905  { "require_sw", "Require software encoding", OFFSET(require_sw), AV_OPT_TYPE_BOOL, \
2906  { .i64 = 0 }, 0, 1, VE }, \
2907  { "realtime", "Hint that encoding should happen in real-time if not faster (e.g. capturing from camera).", \
2908  OFFSET(realtime), AV_OPT_TYPE_BOOL, { .i64 = 0 }, -1, 1, VE }, \
2909  { "frames_before", "Other frames will come before the frames in this session. This helps smooth concatenation issues.", \
2910  OFFSET(frames_before), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VE }, \
2911  { "frames_after", "Other frames will come after the frames in this session. This helps smooth concatenation issues.", \
2912  OFFSET(frames_after), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VE }, \
2913  { "prio_speed", "prioritize encoding speed", OFFSET(prio_speed), AV_OPT_TYPE_BOOL, \
2914  { .i64 = -1 }, -1, 1, VE }, \
2915  { "power_efficient", "Set to 1 to enable more power-efficient encoding if supported.", \
2916  OFFSET(power_efficient), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, 1, VE }, \
2917  { "spatial_aq", "Set to 1 to enable spatial AQ if supported.", \
2918  OFFSET(spatialaq), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, 1, VE }, \
2919  { "max_ref_frames", \
2920  "Sets the maximum number of reference frames. This only has an effect when the value is less than the maximum allowed by the profile/level.", \
2921  OFFSET(max_ref_frames), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, VE },
2922 
2924  HW_CONFIG_ENCODER_FRAMES(VIDEOTOOLBOX, VIDEOTOOLBOX),
2925  NULL,
2926 };
2927 
2928 #define OFFSET(x) offsetof(VTEncContext, x)
2929 static const AVOption h264_options[] = {
2930  { "profile", "Profile", OFFSET(profile), AV_OPT_TYPE_INT, { .i64 = AV_PROFILE_UNKNOWN }, AV_PROFILE_UNKNOWN, INT_MAX, VE, .unit = "profile" },
2931  { "baseline", "Baseline Profile", 0, AV_OPT_TYPE_CONST, { .i64 = AV_PROFILE_H264_BASELINE }, INT_MIN, INT_MAX, VE, .unit = "profile" },
2932  { "constrained_baseline", "Constrained Baseline Profile", 0, AV_OPT_TYPE_CONST, { .i64 = AV_PROFILE_H264_CONSTRAINED_BASELINE }, INT_MIN, INT_MAX, VE, .unit = "profile" },
2933  { "main", "Main Profile", 0, AV_OPT_TYPE_CONST, { .i64 = AV_PROFILE_H264_MAIN }, INT_MIN, INT_MAX, VE, .unit = "profile" },
2934  { "high", "High Profile", 0, AV_OPT_TYPE_CONST, { .i64 = AV_PROFILE_H264_HIGH }, INT_MIN, INT_MAX, VE, .unit = "profile" },
2935  { "constrained_high", "Constrained High Profile", 0, AV_OPT_TYPE_CONST, { .i64 = H264_PROFILE_CONSTRAINED_HIGH }, INT_MIN, INT_MAX, VE, .unit = "profile" },
2936  { "extended", "Extend Profile", 0, AV_OPT_TYPE_CONST, { .i64 = AV_PROFILE_H264_EXTENDED }, INT_MIN, INT_MAX, VE, .unit = "profile" },
2937 
2938  { "level", "Level", OFFSET(level), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 52, VE, .unit = "level" },
2939  { "1.3", "Level 1.3, only available with Baseline Profile", 0, AV_OPT_TYPE_CONST, { .i64 = 13 }, INT_MIN, INT_MAX, VE, .unit = "level" },
2940  { "3.0", "Level 3.0", 0, AV_OPT_TYPE_CONST, { .i64 = 30 }, INT_MIN, INT_MAX, VE, .unit = "level" },
2941  { "3.1", "Level 3.1", 0, AV_OPT_TYPE_CONST, { .i64 = 31 }, INT_MIN, INT_MAX, VE, .unit = "level" },
2942  { "3.2", "Level 3.2", 0, AV_OPT_TYPE_CONST, { .i64 = 32 }, INT_MIN, INT_MAX, VE, .unit = "level" },
2943  { "4.0", "Level 4.0", 0, AV_OPT_TYPE_CONST, { .i64 = 40 }, INT_MIN, INT_MAX, VE, .unit = "level" },
2944  { "4.1", "Level 4.1", 0, AV_OPT_TYPE_CONST, { .i64 = 41 }, INT_MIN, INT_MAX, VE, .unit = "level" },
2945  { "4.2", "Level 4.2", 0, AV_OPT_TYPE_CONST, { .i64 = 42 }, INT_MIN, INT_MAX, VE, .unit = "level" },
2946  { "5.0", "Level 5.0", 0, AV_OPT_TYPE_CONST, { .i64 = 50 }, INT_MIN, INT_MAX, VE, .unit = "level" },
2947  { "5.1", "Level 5.1", 0, AV_OPT_TYPE_CONST, { .i64 = 51 }, INT_MIN, INT_MAX, VE, .unit = "level" },
2948  { "5.2", "Level 5.2", 0, AV_OPT_TYPE_CONST, { .i64 = 52 }, INT_MIN, INT_MAX, VE, .unit = "level" },
2949 
2950  { "coder", "Entropy coding", OFFSET(entropy), AV_OPT_TYPE_INT, { .i64 = VT_ENTROPY_NOT_SET }, VT_ENTROPY_NOT_SET, VT_CABAC, VE, .unit = "coder" },
2951  { "cavlc", "CAVLC entropy coding", 0, AV_OPT_TYPE_CONST, { .i64 = VT_CAVLC }, INT_MIN, INT_MAX, VE, .unit = "coder" },
2952  { "vlc", "CAVLC entropy coding", 0, AV_OPT_TYPE_CONST, { .i64 = VT_CAVLC }, INT_MIN, INT_MAX, VE, .unit = "coder" },
2953  { "cabac", "CABAC entropy coding", 0, AV_OPT_TYPE_CONST, { .i64 = VT_CABAC }, INT_MIN, INT_MAX, VE, .unit = "coder" },
2954  { "ac", "CABAC entropy coding", 0, AV_OPT_TYPE_CONST, { .i64 = VT_CABAC }, INT_MIN, INT_MAX, VE, .unit = "coder" },
2955 
2956  { "a53cc", "Use A53 Closed Captions (if available)", OFFSET(a53_cc), AV_OPT_TYPE_BOOL, {.i64 = 1}, 0, 1, VE },
2957 
2958  { "constant_bit_rate", "Require constant bit rate (macOS 13 or newer)", OFFSET(constant_bit_rate), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VE },
2959  { "max_slice_bytes", "Set the maximum number of bytes in an H.264 slice.", OFFSET(max_slice_bytes), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, INT_MAX, VE },
2961  { NULL },
2962 };
2963 
2964 static const FFCodecDefault vt_defaults[] = {
2965  {"b", "0"},
2966  {"qmin", "-1"},
2967  {"qmax", "-1"},
2968  {NULL},
2969 };
2970 
2972  .class_name = "h264_videotoolbox",
2973  .item_name = av_default_item_name,
2974  .option = h264_options,
2975  .version = LIBAVUTIL_VERSION_INT,
2976 };
2977 
2979  .p.name = "h264_videotoolbox",
2980  CODEC_LONG_NAME("VideoToolbox H.264 Encoder"),
2981  .p.type = AVMEDIA_TYPE_VIDEO,
2982  .p.id = AV_CODEC_ID_H264,
2983  .p.capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_DELAY,
2984  .priv_data_size = sizeof(VTEncContext),
2986  .defaults = vt_defaults,
2987  .init = vtenc_init,
2989  .close = vtenc_close,
2990  .p.priv_class = &h264_videotoolbox_class,
2991  .caps_internal = FF_CODEC_CAP_INIT_CLEANUP,
2992  .hw_configs = vt_encode_hw_configs,
2993 };
2994 
2995 static const AVOption hevc_options[] = {
2996  { "profile", "Profile", OFFSET(profile), AV_OPT_TYPE_INT, { .i64 = AV_PROFILE_UNKNOWN }, AV_PROFILE_UNKNOWN, INT_MAX, VE, .unit = "profile" },
2997  { "main", "Main Profile", 0, AV_OPT_TYPE_CONST, { .i64 = AV_PROFILE_HEVC_MAIN }, INT_MIN, INT_MAX, VE, .unit = "profile" },
2998  { "main10", "Main10 Profile", 0, AV_OPT_TYPE_CONST, { .i64 = AV_PROFILE_HEVC_MAIN_10 }, INT_MIN, INT_MAX, VE, .unit = "profile" },
2999  { "main42210","Main 4:2:2 10 Profile",0, AV_OPT_TYPE_CONST, { .i64 = AV_PROFILE_HEVC_REXT }, INT_MIN, INT_MAX, VE, .unit = "profile" },
3000  { "rext", "Main 4:2:2 10 Profile",0, AV_OPT_TYPE_CONST, { .i64 = AV_PROFILE_HEVC_REXT }, INT_MIN, INT_MAX, VE, .unit = "profile" },
3001 
3002  { "alpha_quality", "Compression quality for the alpha channel", OFFSET(alpha_quality), AV_OPT_TYPE_DOUBLE, { .dbl = 0.0 }, 0.0, 1.0, VE },
3003 
3004  { "constant_bit_rate", "Require constant bit rate (macOS 13 or newer)", OFFSET(constant_bit_rate), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VE },
3005 
3007  { NULL },
3008 };
3009 
3011  .class_name = "hevc_videotoolbox",
3012  .item_name = av_default_item_name,
3013  .option = hevc_options,
3014  .version = LIBAVUTIL_VERSION_INT,
3015 };
3016 
3018  .p.name = "hevc_videotoolbox",
3019  CODEC_LONG_NAME("VideoToolbox H.265 Encoder"),
3020  .p.type = AVMEDIA_TYPE_VIDEO,
3021  .p.id = AV_CODEC_ID_HEVC,
3022  .p.capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_DELAY |
3024  .priv_data_size = sizeof(VTEncContext),
3026  .defaults = vt_defaults,
3027  .color_ranges = AVCOL_RANGE_MPEG | AVCOL_RANGE_JPEG,
3028  .init = vtenc_init,
3030  .close = vtenc_close,
3031  .p.priv_class = &hevc_videotoolbox_class,
3032  .caps_internal = FF_CODEC_CAP_INIT_CLEANUP,
3033  .p.wrapper_name = "videotoolbox",
3034  .hw_configs = vt_encode_hw_configs,
3035 };
3036 
3037 static const AVOption prores_options[] = {
3038  { "profile", "Profile", OFFSET(profile), AV_OPT_TYPE_INT, { .i64 = AV_PROFILE_UNKNOWN }, AV_PROFILE_UNKNOWN, AV_PROFILE_PRORES_XQ, VE, .unit = "profile" },
3039  { "auto", "Automatically determine based on input format", 0, AV_OPT_TYPE_CONST, { .i64 = AV_PROFILE_UNKNOWN }, INT_MIN, INT_MAX, VE, .unit = "profile" },
3040  { "proxy", "ProRes 422 Proxy", 0, AV_OPT_TYPE_CONST, { .i64 = AV_PROFILE_PRORES_PROXY }, INT_MIN, INT_MAX, VE, .unit = "profile" },
3041  { "lt", "ProRes 422 LT", 0, AV_OPT_TYPE_CONST, { .i64 = AV_PROFILE_PRORES_LT }, INT_MIN, INT_MAX, VE, .unit = "profile" },
3042  { "standard", "ProRes 422", 0, AV_OPT_TYPE_CONST, { .i64 = AV_PROFILE_PRORES_STANDARD }, INT_MIN, INT_MAX, VE, .unit = "profile" },
3043  { "hq", "ProRes 422 HQ", 0, AV_OPT_TYPE_CONST, { .i64 = AV_PROFILE_PRORES_HQ }, INT_MIN, INT_MAX, VE, .unit = "profile" },
3044  { "4444", "ProRes 4444", 0, AV_OPT_TYPE_CONST, { .i64 = AV_PROFILE_PRORES_4444 }, INT_MIN, INT_MAX, VE, .unit = "profile" },
3045  { "xq", "ProRes 4444 XQ", 0, AV_OPT_TYPE_CONST, { .i64 = AV_PROFILE_PRORES_XQ }, INT_MIN, INT_MAX, VE, .unit = "profile" },
3046 
3048  { NULL },
3049 };
3050 
3052  .class_name = "prores_videotoolbox",
3053  .item_name = av_default_item_name,
3054  .option = prores_options,
3055  .version = LIBAVUTIL_VERSION_INT,
3056 };
3057 
3059  .p.name = "prores_videotoolbox",
3060  CODEC_LONG_NAME("VideoToolbox ProRes Encoder"),
3061  .p.type = AVMEDIA_TYPE_VIDEO,
3062  .p.id = AV_CODEC_ID_PRORES,
3063  .p.capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_DELAY |
3065  .priv_data_size = sizeof(VTEncContext),
3067  .defaults = vt_defaults,
3068  .color_ranges = AVCOL_RANGE_MPEG | AVCOL_RANGE_JPEG,
3069  .init = vtenc_init,
3071  .close = vtenc_close,
3072  .p.priv_class = &prores_videotoolbox_class,
3073  .caps_internal = FF_CODEC_CAP_INIT_CLEANUP,
3074  .p.wrapper_name = "videotoolbox",
3075  .hw_configs = vt_encode_hw_configs,
3076 };
set_encoder_property_or_log
static void set_encoder_property_or_log(AVCodecContext *avctx, CFStringRef key, const char *print_option_name, CFTypeRef value)
Definition: videotoolboxenc.c:1135
get_vt_hevc_profile_level
static bool get_vt_hevc_profile_level(AVCodecContext *avctx, CFStringRef *profile_level_val)
Definition: videotoolboxenc.c:947
pthread_mutex_t
_fmutex pthread_mutex_t
Definition: os2threads.h:53
hwconfig.h
kVTProfileLevel_H264_Main_5_1
CFStringRef kVTProfileLevel_H264_Main_5_1
Definition: videotoolboxenc.c:104
kCVPixelFormatType_420YpCbCr10BiPlanarFullRange
@ kCVPixelFormatType_420YpCbCr10BiPlanarFullRange
Definition: videotoolboxenc.c:53
av_packet_unref
void av_packet_unref(AVPacket *pkt)
Wipe the packet.
Definition: packet.c:430
kVTCompressionPropertyKey_H264EntropyMode
CFStringRef kVTCompressionPropertyKey_H264EntropyMode
Definition: videotoolboxenc.c:93
ff_alloc_a53_sei
int ff_alloc_a53_sei(const AVFrame *frame, size_t prefix_len, void **data, size_t *sei_size)
Check AVFrame for A53 side data and allocate and fill SEI message with A53 info.
Definition: atsc_a53.c:26
AV_LOG_WARNING
#define AV_LOG_WARNING
Something somehow does not look correct.
Definition: log.h:215
ff_h264_videotoolbox_encoder
const FFCodec ff_h264_videotoolbox_encoder
Definition: videotoolboxenc.c:2978
kCMVideoCodecType_HEVCWithAlpha
@ kCMVideoCodecType_HEVCWithAlpha
Definition: videotoolboxenc.c:49
create_cv_pixel_buffer
static int create_cv_pixel_buffer(AVCodecContext *avctx, const AVFrame *frame, CVPixelBufferRef *cv_img, BufNode *node)
Definition: videotoolboxenc.c:2482
AVPixelFormat
AVPixelFormat
Pixel format.
Definition: pixfmt.h:71
kVTProfileLevel_H264_Extended_AutoLevel
CFStringRef kVTProfileLevel_H264_Extended_AutoLevel
Definition: videotoolboxenc.c:117
name
it s the only field you need to keep assuming you have a context There is some magic you don t need to care about around this just let it vf default minimum maximum flags name is the option name
Definition: writing_filters.txt:88
ff_hevc_videotoolbox_encoder
const FFCodec ff_hevc_videotoolbox_encoder
Definition: videotoolboxenc.c:3017
ExtraSEI::size
size_t size
Definition: videotoolboxenc.c:234
av_map_videotoolbox_color_trc_from_av
CFStringRef av_map_videotoolbox_color_trc_from_av(enum AVColorTransferCharacteristic trc)
Convert an AVColorTransferCharacteristic to a VideoToolbox/CoreVideo color transfer function string.
Definition: hwcontext_videotoolbox.c:490
level
uint8_t level
Definition: svq3.c:205
FF_CODEC_CAP_INIT_CLEANUP
#define FF_CODEC_CAP_INIT_CLEANUP
The codec allows calling the close function for deallocation even if the init function returned a fai...
Definition: codec_internal.h:42
kVTCompressionPropertyKey_RealTime
CFStringRef kVTCompressionPropertyKey_RealTime
Definition: videotoolboxenc.c:125
hevc_pix_fmts
static enum AVPixelFormat hevc_pix_fmts[]
Definition: videotoolboxenc.c:2858
AVERROR
Filter the word “frame” indicates either a video frame or a group of audio as stored in an AVFrame structure Format for each input and each output the list of supported formats For video that means pixel format For audio that means channel sample they are references to shared objects When the negotiation mechanism computes the intersection of the formats supported at each end of a all references to both lists are replaced with a reference to the intersection And when a single format is eventually chosen for a link amongst the remaining all references to the list are updated That means that if a filter requires that its input and output have the same format amongst a supported all it has to do is use a reference to the same list of formats query_formats can leave some formats unset and return AVERROR(EAGAIN) to cause the negotiation mechanism toagain later. That can be used by filters with complex requirements to use the format negotiated on one link to set the formats supported on another. Frame references ownership and permissions
opt.h
get_frame
static int get_frame(AVFilterContext *ctx, int is_second)
Definition: vf_nnedi.c:661
AVCodecContext::colorspace
enum AVColorSpace colorspace
YUV colorspace type.
Definition: avcodec.h:699
AVColorTransferCharacteristic
AVColorTransferCharacteristic
Color Transfer Characteristic.
Definition: pixfmt.h:640
out
FILE * out
Definition: movenc.c:55
color
Definition: vf_paletteuse.c:513
vtenc_populate_extradata
static int vtenc_populate_extradata(AVCodecContext *avctx, CMVideoCodecType codec_type, CFStringRef profile_level, CFNumberRef gamma_level, CFDictionaryRef enc_info, CFDictionaryRef pixel_buffer_info)
Definition: videotoolboxenc.c:2727
av_map_videotoolbox_color_matrix_from_av
CFStringRef av_map_videotoolbox_color_matrix_from_av(enum AVColorSpace space)
Convert an AVColorSpace to a VideoToolbox/CoreVideo color matrix string.
Definition: hwcontext_videotoolbox.c:438
av_frame_get_side_data
AVFrameSideData * av_frame_get_side_data(const AVFrame *frame, enum AVFrameSideDataType type)
Definition: frame.c:693
vtenc_cm_to_avpacket
static int vtenc_cm_to_avpacket(AVCodecContext *avctx, CMSampleBufferRef sample_buffer, AVPacket *pkt, ExtraSEI *sei)
Definition: videotoolboxenc.c:2196
av_pix_fmt_desc_get
const AVPixFmtDescriptor * av_pix_fmt_desc_get(enum AVPixelFormat pix_fmt)
Definition: pixdesc.c:3313
AV_CODEC_CAP_HARDWARE
#define AV_CODEC_CAP_HARDWARE
Codec is backed by a hardware implementation.
Definition: codec.h:145
AV_FRAME_DATA_A53_CC
@ AV_FRAME_DATA_A53_CC
ATSC A53 Part 4 Closed Captions.
Definition: frame.h:59
pthread_mutex_init
static av_always_inline int pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutexattr_t *attr)
Definition: os2threads.h:104
AV_PROFILE_H264_MAIN
#define AV_PROFILE_H264_MAIN
Definition: defs.h:112
VTEncContext::profile
int profile
Definition: videotoolboxenc.c:268
copy_avframe_to_pixel_buffer
static int copy_avframe_to_pixel_buffer(AVCodecContext *avctx, const AVFrame *frame, CVPixelBufferRef cv_img, const size_t *plane_strides, const size_t *plane_rows)
Definition: videotoolboxenc.c:2390
vtenc_output_callback
static void vtenc_output_callback(void *ctx, void *sourceFrameCtx, OSStatus status, VTEncodeInfoFlags flags, CMSampleBufferRef sample_buffer)
Definition: videotoolboxenc.c:738
AV_CODEC_FLAG_QSCALE
#define AV_CODEC_FLAG_QSCALE
Use fixed qscale.
Definition: avcodec.h:224
kVTCompressionPropertyKey_MaximizePowerEfficiency
CFStringRef kVTCompressionPropertyKey_MaximizePowerEfficiency
Definition: videotoolboxenc.c:136
int64_t
long long int64_t
Definition: coverity.c:34
vtenc_free_buf_node
static void vtenc_free_buf_node(BufNode *info)
Definition: videotoolboxenc.c:294
AV_PROFILE_HEVC_MAIN
#define AV_PROFILE_HEVC_MAIN
Definition: defs.h:159
get_vt_h264_profile_level
static bool get_vt_h264_profile_level(AVCodecContext *avctx, CFStringRef *profile_level_val)
Definition: videotoolboxenc.c:818
write_sei
static int write_sei(const ExtraSEI *sei, int sei_type, uint8_t *dst, size_t dst_size)
Definition: videotoolboxenc.c:1949
H264_PROFILE_CONSTRAINED_HIGH
#define H264_PROFILE_CONSTRAINED_HIGH
Definition: videotoolboxenc.c:222
AVFrame
This structure describes decoded (raw) audio or video data.
Definition: frame.h:410
start_code
static const uint8_t start_code[]
Definition: videotoolboxenc.c:230
pixdesc.h
kVTProfileLevel_H264_High_AutoLevel
CFStringRef kVTProfileLevel_H264_High_AutoLevel
Definition: videotoolboxenc.c:115
AVCodecContext::color_trc
enum AVColorTransferCharacteristic color_trc
Color Transfer Characteristic.
Definition: avcodec.h:692
H264_NAL_AUD
@ H264_NAL_AUD
Definition: h264.h:43
AVCOL_RANGE_JPEG
@ AVCOL_RANGE_JPEG
Full range content.
Definition: pixfmt.h:746
internal.h
AVPacket::data
uint8_t * data
Definition: packet.h:539
BufNode::frame_buf
AVBufferRef * frame_buf
Definition: videotoolboxenc.c:240
pthread_mutex_lock
static av_always_inline int pthread_mutex_lock(pthread_mutex_t *mutex)
Definition: os2threads.h:119
AVOption
AVOption.
Definition: opt.h:429
encode.h
get_cm_codec_type
static CMVideoCodecType get_cm_codec_type(AVCodecContext *avctx, int profile, double alpha_quality)
Definition: videotoolboxenc.c:520
kVTProfileLevel_H264_High_4_0
CFStringRef kVTProfileLevel_H264_High_4_0
Definition: videotoolboxenc.c:110
data
const char data[16]
Definition: mxf.c:149
FFCodec
Definition: codec_internal.h:127
VTEncContext::lock
pthread_mutex_t lock
Definition: videotoolboxenc.c:254
kVTProfileLevel_H264_ConstrainedBaseline_AutoLevel
CFStringRef kVTProfileLevel_H264_ConstrainedBaseline_AutoLevel
Definition: videotoolboxenc.c:118
AV_PIX_FMT_BGRA
@ AV_PIX_FMT_BGRA
packed BGRA 8:8:8:8, 32bpp, BGRABGRA...
Definition: pixfmt.h:102
av_buffer_ref
AVBufferRef * av_buffer_ref(const AVBufferRef *buf)
Create a new reference to an AVBuffer.
Definition: buffer.c:103
vtenc_create_encoder
static int vtenc_create_encoder(AVCodecContext *avctx, CMVideoCodecType codec_type, CFStringRef profile_level, CFNumberRef gamma_level, CFDictionaryRef enc_info, CFDictionaryRef pixel_buffer_info, bool constant_bit_rate, VTCompressionSessionRef *session)
Definition: videotoolboxenc.c:1176
AVCodecContext::qmax
int qmax
maximum quantizer
Definition: avcodec.h:1281
bit_depth
static void bit_depth(AudioStatsContext *s, const uint64_t *const mask, uint8_t *depth)
Definition: af_astats.c:246
codec_type
enum AVMediaType codec_type
Definition: rtp.c:37
AV_PKT_FLAG_KEY
#define AV_PKT_FLAG_KEY
The packet contains a keyframe.
Definition: packet.h:594
quality
trying all byte sequences megabyte in length and selecting the best looking sequence will yield cases to try But a word about quality
Definition: rate_distortion.txt:12
kVTCompressionPropertyKey_MinAllowedFrameQP
CFStringRef kVTCompressionPropertyKey_MinAllowedFrameQP
Definition: videotoolboxenc.c:139
av_malloc
#define av_malloc(s)
Definition: tableprint_vlc.h:30
AV_CODEC_FLAG_GLOBAL_HEADER
#define AV_CODEC_FLAG_GLOBAL_HEADER
Place global headers in extradata instead of every keyframe.
Definition: avcodec.h:338
set_encoder_int_property_or_log
static int set_encoder_int_property_or_log(AVCodecContext *avctx, CFStringRef key, const char *print_option_name, int value)
Definition: videotoolboxenc.c:1157
AV_PROFILE_PRORES_STANDARD
#define AV_PROFILE_PRORES_STANDARD
Definition: defs.h:183
kVTCompressionPropertyKey_AllowOpenGOP
CFStringRef kVTCompressionPropertyKey_AllowOpenGOP
Definition: videotoolboxenc.c:135
copy_replace_length_codes
static int copy_replace_length_codes(AVCodecContext *avctx, size_t length_code_size, CMSampleBufferRef sample_buffer, ExtraSEI *sei, uint8_t *dst_data, size_t dst_size)
Copies NAL units and replaces length codes with H.264 Annex B start codes.
Definition: videotoolboxenc.c:2022
AV_PROFILE_H264_EXTENDED
#define AV_PROFILE_H264_EXTENDED
Definition: defs.h:113
av_pix_fmt_count_planes
int av_pix_fmt_count_planes(enum AVPixelFormat pix_fmt)
Definition: pixdesc.c:3353
AV_PROFILE_PRORES_HQ
#define AV_PROFILE_PRORES_HQ
Definition: defs.h:184
FFCodecDefault
Definition: codec_internal.h:96
vtenc_get_frame_info
static void vtenc_get_frame_info(CMSampleBufferRef buffer, bool *is_key_frame)
Definition: videotoolboxenc.c:1798
vtenc_reset
static void vtenc_reset(VTEncContext *vtctx)
Definition: videotoolboxenc.c:385
FFCodec::p
AVCodec p
The public AVCodec.
Definition: codec_internal.h:131
get_cv_pixel_format
static int get_cv_pixel_format(AVCodecContext *avctx, enum AVPixelFormat fmt, enum AVColorRange range, int *av_pixel_format, int *range_guessed)
Definition: videotoolboxenc.c:999
vtenc_close
static av_cold int vtenc_close(AVCodecContext *avctx)
Definition: videotoolboxenc.c:2830
AVCOL_TRC_GAMMA28
@ AVCOL_TRC_GAMMA28
also ITU-R BT470BG
Definition: pixfmt.h:646
add_color_attr
static void add_color_attr(AVCodecContext *avctx, CFMutableDictionaryRef dict)
Definition: videotoolboxenc.c:1023
AVCodecContext::flags
int flags
AV_CODEC_FLAG_*.
Definition: avcodec.h:508
VTEncContext::allow_sw
int allow_sw
Definition: videotoolboxenc.c:276
kCVImageBufferYCbCrMatrix_ITU_R_2020
CFStringRef kCVImageBufferYCbCrMatrix_ITU_R_2020
Definition: videotoolboxenc.c:91
type
it s the only field you need to keep assuming you have a context There is some magic you don t need to care about around this just let it vf type
Definition: writing_filters.txt:86
AVERROR_BUFFER_TOO_SMALL
#define AVERROR_BUFFER_TOO_SMALL
Buffer too small.
Definition: error.h:53
AV_CODEC_FLAG_LOW_DELAY
#define AV_CODEC_FLAG_LOW_DELAY
Force low delay.
Definition: avcodec.h:334
pts
static int64_t pts
Definition: transcode_aac.c:644
VTEncContext::flushing
bool flushing
Definition: videotoolboxenc.c:281
FF_CODEC_ENCODE_CB
#define FF_CODEC_ENCODE_CB(func)
Definition: codec_internal.h:353
create_encoder_dict_h264
static int create_encoder_dict_h264(const AVFrame *frame, CFDictionaryRef *dict_out)
Definition: videotoolboxenc.c:2586
av_reduce
int av_reduce(int *dst_num, int *dst_den, int64_t num, int64_t den, int64_t max)
Reduce a fraction.
Definition: rational.c:35
AVRational::num
int num
Numerator.
Definition: rational.h:59
AVCOL_TRC_GAMMA22
@ AVCOL_TRC_GAMMA22
also ITU-R BT470M / ITU-R BT1700 625 PAL & SECAM
Definition: pixfmt.h:645
kVTProfileLevel_HEVC_Main10_AutoLevel
CFStringRef kVTProfileLevel_HEVC_Main10_AutoLevel
Definition: videotoolboxenc.c:122
h264_options
static const AVOption h264_options[]
Definition: videotoolboxenc.c:2929
av_map_videotoolbox_color_primaries_from_av
CFStringRef av_map_videotoolbox_color_primaries_from_av(enum AVColorPrimaries pri)
Convert an AVColorPrimaries to a VideoToolbox/CoreVideo color primaries string.
Definition: hwcontext_videotoolbox.c:465
VTEncContext::realtime
int realtime
Definition: videotoolboxenc.c:271
avassert.h
get_params_size
static int get_params_size(AVCodecContext *avctx, CMVideoFormatDescriptionRef vid_fmt, size_t *size)
Get the parameter sets from a CMSampleBufferRef.
Definition: videotoolboxenc.c:571
AVCodecContext::color_primaries
enum AVColorPrimaries color_primaries
Chromaticity coordinates of the source primaries.
Definition: avcodec.h:685
compat_keys
static struct @257 compat_keys
VTEncContext::dts_delta
int64_t dts_delta
Definition: videotoolboxenc.c:266
pkt
AVPacket * pkt
Definition: movenc.c:60
AV_LOG_ERROR
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition: log.h:209
AVFrameSideData::size
size_t size
Definition: frame.h:268
av_cold
#define av_cold
Definition: attributes.h:90
AV_PROFILE_UNKNOWN
#define AV_PROFILE_UNKNOWN
Definition: defs.h:65
kVTProfileLevel_H264_ConstrainedHigh_AutoLevel
CFStringRef kVTProfileLevel_H264_ConstrainedHigh_AutoLevel
Definition: videotoolboxenc.c:119
VTEncContext::first_pts
int64_t first_pts
Definition: videotoolboxenc.c:265
avc_pix_fmts
static enum AVPixelFormat avc_pix_fmts[]
Definition: videotoolboxenc.c:2851
get_cv_gamma
static int get_cv_gamma(AVCodecContext *avctx, CFNumberRef *gamma_level)
Definition: videotoolboxenc.c:1112
kVTProfileLevel_H264_High_4_2
CFStringRef kVTProfileLevel_H264_High_4_2
Definition: videotoolboxenc.c:112
AVCodecContext::extradata_size
int extradata_size
Definition: avcodec.h:538
AVCodecContext::has_b_frames
int has_b_frames
Size of the frame reordering buffer in the decoder.
Definition: avcodec.h:737
VTEncContext::frames_after
int frames_after
Definition: videotoolboxenc.c:273
vt_encode_hw_configs
static const AVCodecHWConfigInternal *const vt_encode_hw_configs[]
Definition: videotoolboxenc.c:2923
VTEncContext::async_error
int async_error
Definition: videotoolboxenc.c:257
hevc_options
static const AVOption hevc_options[]
Definition: videotoolboxenc.c:2995
AVCodecContext::global_quality
int global_quality
Global quality for codecs which cannot change it per frame.
Definition: avcodec.h:1257
prores_pix_fmts
static enum AVPixelFormat prores_pix_fmts[]
Definition: videotoolboxenc.c:2868
pthread_mutex_unlock
static av_always_inline int pthread_mutex_unlock(pthread_mutex_t *mutex)
Definition: os2threads.h:126
VT_CABAC
@ VT_CABAC
Definition: videotoolboxenc.c:227
prores_options
static const AVOption prores_options[]
Definition: videotoolboxenc.c:3037
kVTQPModulationLevel_Disable
@ kVTQPModulationLevel_Disable
Definition: videotoolboxenc.c:59
AV_OPT_TYPE_DOUBLE
@ AV_OPT_TYPE_DOUBLE
Underlying C type is double.
Definition: opt.h:267
VTEncContext::cv_sample_sent
pthread_cond_t cv_sample_sent
Definition: videotoolboxenc.c:255
VTEncContext::transfer_function
CFStringRef transfer_function
Definition: videotoolboxenc.c:251
info
MIPS optimizations info
Definition: mips.txt:2
av_assert0
#define av_assert0(cond)
assert() equivalent, that is always enabled.
Definition: avassert.h:40
AV_LOG_DEBUG
#define AV_LOG_DEBUG
Stuff which is only useful for libav* developers.
Definition: log.h:230
VTEncContext::alpha_quality
double alpha_quality
Definition: videotoolboxenc.c:278
CMVideoFormatDescriptionGetHEVCParameterSetAtIndex
getParameterSetAtIndex CMVideoFormatDescriptionGetHEVCParameterSetAtIndex
Definition: videotoolboxenc.c:141
kCVPixelFormatType_420YpCbCr10BiPlanarVideoRange
@ kCVPixelFormatType_420YpCbCr10BiPlanarVideoRange
Definition: videotoolboxenc.c:54
AV_PIX_FMT_FLAG_ALPHA
#define AV_PIX_FMT_FLAG_ALPHA
The pixel format has an alpha channel.
Definition: pixdesc.h:147
ctx
AVFormatContext * ctx
Definition: movenc.c:49
SEI_TYPE_USER_DATA_REGISTERED_ITU_T_T35
@ SEI_TYPE_USER_DATA_REGISTERED_ITU_T_T35
Definition: sei.h:34
kVTCompressionPropertyKey_ConstantBitRate
CFStringRef kVTCompressionPropertyKey_ConstantBitRate
Definition: videotoolboxenc.c:128
AV_PIX_FMT_YUV420P
@ AV_PIX_FMT_YUV420P
planar YUV 4:2:0, 12bpp, (1 Cr & Cb sample per 2x2 Y samples)
Definition: pixfmt.h:73
AVCodecContext::rc_max_rate
int64_t rc_max_rate
maximum bitrate
Definition: avcodec.h:1310
key
const char * key
Definition: hwcontext_opencl.c:189
AV_CODEC_ID_H264
@ AV_CODEC_ID_H264
Definition: codec_id.h:79
CODEC_LONG_NAME
#define CODEC_LONG_NAME(str)
Definition: codec_internal.h:326
AVCodecContext::codec_id
enum AVCodecID codec_id
Definition: avcodec.h:461
getParameterSetAtIndex
OSStatus(* getParameterSetAtIndex)(CMFormatDescriptionRef videoDesc, size_t parameterSetIndex, const uint8_t **parameterSetPointerOut, size_t *parameterSetSizeOut, size_t *parameterSetCountOut, int *NALUnitHeaderLengthOut)
Definition: videotoolboxenc.c:66
VTEncContext::max_slice_bytes
int max_slice_bytes
Definition: videotoolboxenc.c:288
kVTCompressionPropertyKey_EncoderID
CFStringRef kVTCompressionPropertyKey_EncoderID
Definition: videotoolboxenc.c:129
set_extradata
static int set_extradata(AVCodecContext *avctx, CMSampleBufferRef sample_buffer)
Definition: videotoolboxenc.c:689
av_color_range_name
const char * av_color_range_name(enum AVColorRange range)
Definition: pixdesc.c:3629
VTEncContext::frame_ct_in
int64_t frame_ct_in
Definition: videotoolboxenc.c:263
kVTVideoEncoderSpecification_RequireHardwareAcceleratedVideoEncoder
CFStringRef kVTVideoEncoderSpecification_RequireHardwareAcceleratedVideoEncoder
Definition: videotoolboxenc.c:133
LIBAVUTIL_VERSION_INT
#define LIBAVUTIL_VERSION_INT
Definition: version.h:85
AVClass
Describe the class of an AVClass context structure.
Definition: log.h:75
NULL
#define NULL
Definition: coverity.c:32
vtenc_q_push
static void vtenc_q_push(VTEncContext *vtctx, BufNode *info)
Definition: videotoolboxenc.c:461
kVTProfileLevel_HEVC_Main_AutoLevel
CFStringRef kVTProfileLevel_HEVC_Main_AutoLevel
Definition: videotoolboxenc.c:121
AVCodecContext::color_range
enum AVColorRange color_range
MPEG vs JPEG YUV range.
Definition: avcodec.h:709
CODEC_PIXFMTS_ARRAY
#define CODEC_PIXFMTS_ARRAY(array)
Definition: codec_internal.h:387
av_buffer_unref
void av_buffer_unref(AVBufferRef **buf)
Free a given reference and automatically free the buffer if there are no more references to it.
Definition: buffer.c:139
prores_videotoolbox_class
static const AVClass prores_videotoolbox_class
Definition: videotoolboxenc.c:3051
BufNode
Definition: videotoolboxenc.c:237
VTEncContext::spatialaq
int spatialaq
Definition: videotoolboxenc.c:291
AVRational
Rational number (pair of numerator and denominator).
Definition: rational.h:58
kVTProfileLevel_H264_Baseline_5_2
CFStringRef kVTProfileLevel_H264_Baseline_5_2
Definition: videotoolboxenc.c:101
h264_videotoolbox_class
static const AVClass h264_videotoolbox_class
Definition: videotoolboxenc.c:2971
VTEncContext::max_ref_frames
int max_ref_frames
Definition: videotoolboxenc.c:290
AVCodecContext::bit_rate
int64_t bit_rate
the average bitrate
Definition: avcodec.h:501
av_default_item_name
const char * av_default_item_name(void *ptr)
Return the context name.
Definition: log.c:239
AV_PICTURE_TYPE_I
@ AV_PICTURE_TYPE_I
Intra.
Definition: avutil.h:279
AV_PIX_FMT_P410
#define AV_PIX_FMT_P410
Definition: pixfmt.h:596
create_cv_pixel_buffer_info
static int create_cv_pixel_buffer_info(AVCodecContext *avctx, CFMutableDictionaryRef *dict)
Definition: videotoolboxenc.c:1045
pthread_once
static av_always_inline int pthread_once(pthread_once_t *once_control, void(*init_routine)(void))
Definition: os2threads.h:210
vtenc_qscale_enabled
static bool vtenc_qscale_enabled(void)
Definition: videotoolboxenc.c:1130
VTH264Entropy
VTH264Entropy
Definition: videotoolboxenc.c:224
sei
static int FUNC() sei(CodedBitstreamContext *ctx, RWContext *rw, H264RawSEI *current)
Definition: cbs_h264_syntax_template.c:858
ExtraSEI::data
void * data
Definition: videotoolboxenc.c:233
AV_PROFILE_HEVC_MAIN_10
#define AV_PROFILE_HEVC_MAIN_10
Definition: defs.h:160
AV_PROFILE_HEVC_REXT
#define AV_PROFILE_HEVC_REXT
Definition: defs.h:162
AV_PROFILE_PRORES_LT
#define AV_PROFILE_PRORES_LT
Definition: defs.h:182
AVCodecID
AVCodecID
Identify the syntax and semantics of the bitstream.
Definition: codec_id.h:49
AVCodecContext::time_base
AVRational time_base
This is the fundamental unit of time (in seconds) in terms of which frame timestamps are represented.
Definition: avcodec.h:558
hwcontext_videotoolbox.h
VTEncContext::a53_cc
int a53_cc
Definition: videotoolboxenc.c:286
VT_ENTROPY_NOT_SET
@ VT_ENTROPY_NOT_SET
Definition: videotoolboxenc.c:225
AV_CODEC_CAP_DR1
#define AV_CODEC_CAP_DR1
Codec uses get_buffer() or get_encode_buffer() for allocating buffers and supports custom allocators.
Definition: codec.h:52
AVPacket::size
int size
Definition: packet.h:540
AVCodecContext::gop_size
int gop_size
the number of pictures in a group of pictures, or 0 for intra_only
Definition: avcodec.h:1045
kVTCompressionPropertyKey_SpatialAdaptiveQPLevel
CFStringRef kVTCompressionPropertyKey_SpatialAdaptiveQPLevel
Definition: videotoolboxenc.c:130
codec_internal.h
dst
uint8_t ptrdiff_t const uint8_t ptrdiff_t int intptr_t intptr_t int int16_t * dst
Definition: dsp.h:83
av_bswap32
#define av_bswap32
Definition: bswap.h:47
vt_release_num
static void vt_release_num(CFNumberRef *refPtr)
NULL-safe release of *refPtr, and sets value to NULL.
Definition: videotoolboxenc.c:351
kCVImageBufferTransferFunction_ITU_R_2020
CFStringRef kCVImageBufferTransferFunction_ITU_R_2020
Definition: videotoolboxenc.c:90
size
int size
Definition: twinvq_data.h:10344
color
static const uint32_t color[16+AV_CLASS_CATEGORY_NB]
Definition: log.c:96
AV_NUM_DATA_POINTERS
#define AV_NUM_DATA_POINTERS
Definition: frame.h:411
MKBETAG
#define MKBETAG(a, b, c, d)
Definition: macros.h:56
VTEncContext::frame_ct_out
int64_t frame_ct_out
Definition: videotoolboxenc.c:262
VTEncContext::entropy
int entropy
Definition: videotoolboxenc.c:270
AV_PIX_FMT_AYUV64
#define AV_PIX_FMT_AYUV64
Definition: pixfmt.h:580
kVTProfileLevel_H264_Baseline_4_2
CFStringRef kVTProfileLevel_H264_Baseline_4_2
Definition: videotoolboxenc.c:98
kVTProfileLevel_H264_Main_5_2
CFStringRef kVTProfileLevel_H264_Main_5_2
Definition: videotoolboxenc.c:105
hevc_videotoolbox_class
static const AVClass hevc_videotoolbox_class
Definition: videotoolboxenc.c:3010
AVCodecHWConfigInternal
Definition: hwconfig.h:25
range
enum AVColorRange range
Definition: mediacodec_wrapper.c:2594
AV_PIX_FMT_NV16
@ AV_PIX_FMT_NV16
interleaved chroma YUV 4:2:2, 16bpp, (1 Cr & Cb sample per 2x1 Y samples)
Definition: pixfmt.h:198
kVTProfileLevel_H264_Main_AutoLevel
CFStringRef kVTProfileLevel_H264_Main_AutoLevel
Definition: videotoolboxenc.c:106
AVPacket::dts
int64_t dts
Decompression timestamp in AVStream->time_base units; the time at which the packet is decompressed.
Definition: packet.h:538
AV_PROFILE_PRORES_4444
#define AV_PROFILE_PRORES_4444
Definition: defs.h:185
kCMVideoCodecType_HEVC
@ kCMVideoCodecType_HEVC
Definition: videotoolboxenc.c:45
AVERROR_EXTERNAL
#define AVERROR_EXTERNAL
Generic error in an external library.
Definition: error.h:59
offset
it s the only field you need to keep assuming you have a context There is some magic you don t need to care about around this just let it vf offset
Definition: writing_filters.txt:86
kVTCompressionPropertyKey_ReferenceBufferCount
CFStringRef kVTCompressionPropertyKey_ReferenceBufferCount
Definition: videotoolboxenc.c:137
VTEncContext::frames_before
int frames_before
Definition: videotoolboxenc.c:272
ExtraSEI
Definition: videotoolboxenc.c:232
AVPacket::flags
int flags
A combination of AV_PKT_FLAG values.
Definition: packet.h:545
AV_PIX_FMT_P216
#define AV_PIX_FMT_P216
Definition: pixfmt.h:599
AV_PIX_FMT_P210
#define AV_PIX_FMT_P210
Definition: pixfmt.h:595
vt_dump_encoder
static int vt_dump_encoder(AVCodecContext *avctx)
Definition: videotoolboxenc.c:306
kVTCompressionPropertyKey_PrioritizeEncodingSpeedOverQuality
CFStringRef kVTCompressionPropertyKey_PrioritizeEncodingSpeedOverQuality
Definition: videotoolboxenc.c:127
AV_PROFILE_PRORES_PROXY
#define AV_PROFILE_PRORES_PROXY
Definition: defs.h:181
pthread_cond_destroy
static av_always_inline int pthread_cond_destroy(pthread_cond_t *cond)
Definition: os2threads.h:144
vt_defaults
static const FFCodecDefault vt_defaults[]
Definition: videotoolboxenc.c:2964
AV_LOG_INFO
#define AV_LOG_INFO
Standard information.
Definition: log.h:220
kVTH264EntropyMode_CABAC
CFStringRef kVTH264EntropyMode_CABAC
Definition: videotoolboxenc.c:95
VTEncContext::get_param_set_func
getParameterSetAtIndex get_param_set_func
Definition: videotoolboxenc.c:252
VTEncContext::power_efficient
int power_efficient
Definition: videotoolboxenc.c:289
pthread_mutex_destroy
static av_always_inline int pthread_mutex_destroy(pthread_mutex_t *mutex)
Definition: os2threads.h:112
kVTProfileLevel_H264_Baseline_AutoLevel
CFStringRef kVTProfileLevel_H264_Baseline_AutoLevel
Definition: videotoolboxenc.c:102
HW_CONFIG_ENCODER_FRAMES
#define HW_CONFIG_ENCODER_FRAMES(format, device_type_)
Definition: hwconfig.h:98
AV_PIX_FMT_VIDEOTOOLBOX
@ AV_PIX_FMT_VIDEOTOOLBOX
hardware decoding through Videotoolbox
Definition: pixfmt.h:305
h264_sei.h
TARGET_CPU_ARM64
#define TARGET_CPU_ARM64
Definition: videotoolboxenc.c:63
AVCodecContext::bits_per_coded_sample
int bits_per_coded_sample
bits per sample/pixel from the demuxer (needed for huffyuv).
Definition: avcodec.h:1586
set_async_error
static void set_async_error(VTEncContext *vtctx, int err)
Definition: videotoolboxenc.c:360
COMMON_OPTIONS
#define COMMON_OPTIONS
Definition: videotoolboxenc.c:2902
BufNode::sei
ExtraSEI sei
Definition: videotoolboxenc.c:239
i
#define i(width, name, range_min, range_max)
Definition: cbs_h2645.c:256
AVPacket::pts
int64_t pts
Presentation timestamp in AVStream->time_base units; the time at which the decompressed packet will b...
Definition: packet.h:532
kVTVideoEncoderSpecification_EnableLowLatencyRateControl
CFStringRef kVTVideoEncoderSpecification_EnableLowLatencyRateControl
Definition: videotoolboxenc.c:134
AVCodecContext::extradata
uint8_t * extradata
Out-of-band global headers that may be used by some codecs.
Definition: avcodec.h:537
VTEncContext::ycbcr_matrix
CFStringRef ycbcr_matrix
Definition: videotoolboxenc.c:249
AV_PIX_FMT_NV24
@ AV_PIX_FMT_NV24
planar YUV 4:4:4, 24bpp, 1 plane for Y and 1 plane for the UV components, which are interleaved (firs...
Definition: pixfmt.h:371
GET_SYM
#define GET_SYM(symbol, defaultVal)
Definition: videotoolboxenc.c:144
loadVTEncSymbols
static void loadVTEncSymbols(void)
Definition: videotoolboxenc.c:155
copy_emulation_prev
static int copy_emulation_prev(const uint8_t *src, size_t src_size, uint8_t *dst, ssize_t dst_offset, size_t dst_size)
Copies the data inserting emulation prevention bytes as needed.
Definition: videotoolboxenc.c:1898
VTEncContext::has_b_frames
int has_b_frames
Definition: videotoolboxenc.c:282
AV_CODEC_ID_HEVC
@ AV_CODEC_ID_HEVC
Definition: codec_id.h:228
value
it s the only field you need to keep assuming you have a context There is some magic you don t need to care about around this just let it vf default value
Definition: writing_filters.txt:86
H264_NAL_SEI
@ H264_NAL_SEI
Definition: h264.h:40
kVTProfileLevel_H264_Baseline_5_1
CFStringRef kVTProfileLevel_H264_Baseline_5_1
Definition: videotoolboxenc.c:100
count_nalus
static int count_nalus(size_t length_code_size, CMSampleBufferRef sample_buffer, int *count)
Definition: videotoolboxenc.c:477
vtenc_q_pop
static int vtenc_q_pop(VTEncContext *vtctx, bool wait, CMSampleBufferRef *buf, ExtraSEI *sei)
Definition: videotoolboxenc.c:413
VTEncContext::level
int level
Definition: videotoolboxenc.c:269
is_post_sei_nal_type
static int is_post_sei_nal_type(int nal_type)
Definition: videotoolboxenc.c:1825
BufNode::next
struct BufNode * next
Definition: videotoolboxenc.c:241
av_mallocz
void * av_mallocz(size_t size)
Allocate a memory block with alignment suitable for all memory accesses (including vectors if availab...
Definition: mem.c:256
AVCodec::name
const char * name
Name of the codec implementation.
Definition: codec.h:194
len
int len
Definition: vorbis_enc_data.h:426
pthread_cond_t
Definition: os2threads.h:58
profile
int profile
Definition: mxfenc.c:2250
AVCodecContext::height
int height
Definition: avcodec.h:632
AVCodecContext::pix_fmt
enum AVPixelFormat pix_fmt
Pixel format, see AV_PIX_FMT_xxx.
Definition: avcodec.h:671
AVCOL_RANGE_MPEG
@ AVCOL_RANGE_MPEG
Narrow or limited range content.
Definition: pixfmt.h:729
once_ctrl
static pthread_once_t once_ctrl
Definition: videotoolboxenc.c:153
kVTProfileLevel_H264_Baseline_5_0
CFStringRef kVTProfileLevel_H264_Baseline_5_0
Definition: videotoolboxenc.c:99
avcodec.h
AV_CODEC_FLAG_CLOSED_GOP
#define AV_CODEC_FLAG_CLOSED_GOP
Definition: avcodec.h:352
VTEncContext
Definition: videotoolboxenc.c:244
AV_PIX_FMT_NV12
@ AV_PIX_FMT_NV12
planar YUV 4:2:0, 12bpp, 1 plane for Y and 1 plane for the UV components, which are interleaved (firs...
Definition: pixfmt.h:96
AVClass::class_name
const char * class_name
The name of the class; usually it is the same name as the context structure type to which the AVClass...
Definition: log.h:80
frame
these buffered frames must be flushed immediately if a new input produces new the filter must not call request_frame to get more It must just process the frame or queue it The task of requesting more frames is left to the filter s request_frame method or the application If a filter has several the filter must be ready for frames arriving randomly on any input any filter with several inputs will most likely require some kind of queuing mechanism It is perfectly acceptable to have a limited queue and to drop frames when the inputs are too unbalanced request_frame For filters that do not use the this method is called when a frame is wanted on an output For a it should directly call filter_frame on the corresponding output For a if there are queued frames already one of these frames should be pushed If the filter should request a frame on one of its repeatedly until at least one frame has been pushed Return or at least make progress towards producing a frame
Definition: filter_design.txt:264
atsc_a53.h
AV_PROFILE_H264_BASELINE
#define AV_PROFILE_H264_BASELINE
Definition: defs.h:110
kVTProfileLevel_H264_Baseline_4_0
CFStringRef kVTProfileLevel_H264_Baseline_4_0
Definition: videotoolboxenc.c:97
clear_frame_queue
static void clear_frame_queue(VTEncContext *vtctx)
Definition: videotoolboxenc.c:380
vtenc_configure_encoder
static int vtenc_configure_encoder(AVCodecContext *avctx)
Definition: videotoolboxenc.c:1633
kVTProfileLevel_H264_High_5_2
CFStringRef kVTProfileLevel_H264_High_5_2
Definition: videotoolboxenc.c:114
VTEncContext::session
VTCompressionSessionRef session
Definition: videotoolboxenc.c:247
AV_INPUT_BUFFER_PADDING_SIZE
#define AV_INPUT_BUFFER_PADDING_SIZE
Definition: defs.h:40
pthread_cond_signal
static av_always_inline int pthread_cond_signal(pthread_cond_t *cond)
Definition: os2threads.h:152
AV_PIX_FMT_UYVY422
@ AV_PIX_FMT_UYVY422
packed YUV 4:2:2, 16bpp, Cb Y0 Cr Y1
Definition: pixfmt.h:88
AVCodecContext
main external API structure.
Definition: avcodec.h:451
AV_PROFILE_H264_HIGH
#define AV_PROFILE_H264_HIGH
Definition: defs.h:114
status
ov_status_e status
Definition: dnn_backend_openvino.c:100
kCVImageBufferColorPrimaries_ITU_R_2020
CFStringRef kCVImageBufferColorPrimaries_ITU_R_2020
Definition: videotoolboxenc.c:89
kVTH264EntropyMode_CAVLC
CFStringRef kVTH264EntropyMode_CAVLC
Definition: videotoolboxenc.c:94
kVTProfileLevel_HEVC_Main42210_AutoLevel
CFStringRef kVTProfileLevel_HEVC_Main42210_AutoLevel
Definition: videotoolboxenc.c:123
kVTProfileLevel_H264_High_3_1
CFStringRef kVTProfileLevel_H264_High_3_1
Definition: videotoolboxenc.c:108
kVTVideoEncoderSpecification_EnableHardwareAcceleratedVideoEncoder
CFStringRef kVTVideoEncoderSpecification_EnableHardwareAcceleratedVideoEncoder
Definition: videotoolboxenc.c:132
buffer
the frame and frame reference mechanism is intended to as much as expensive copies of that data while still allowing the filters to produce correct results The data is stored in buffers represented by AVFrame structures Several references can point to the same frame buffer
Definition: filter_design.txt:49
ff_get_encode_buffer
int ff_get_encode_buffer(AVCodecContext *avctx, AVPacket *avpkt, int64_t size, int flags)
Get a buffer for a packet.
Definition: encode.c:106
AVCodecContext::qmin
int qmin
minimum quantizer
Definition: avcodec.h:1274
AVRational::den
int den
Denominator.
Definition: rational.h:60
AV_PIX_FMT_NONE
@ AV_PIX_FMT_NONE
Definition: pixfmt.h:72
AV_OPT_TYPE_INT
@ AV_OPT_TYPE_INT
Underlying C type is int.
Definition: opt.h:259
AVCodecContext::profile
int profile
profile
Definition: avcodec.h:1658
VTEncContext::prio_speed
int prio_speed
Definition: videotoolboxenc.c:279
get_cv_pixel_info
static int get_cv_pixel_info(AVCodecContext *avctx, const AVFrame *frame, int *color, int *plane_count, size_t *widths, size_t *heights, size_t *strides, size_t *contiguous_buf_size)
Definition: videotoolboxenc.c:2326
AV_CODEC_CAP_DELAY
#define AV_CODEC_CAP_DELAY
Encoder or decoder requires flushing with NULL input at the end in order to give the complete and cor...
Definition: codec.h:76
pthread_once_t
Definition: os2threads.h:66
VTEncContext::supported_props
CFDictionaryRef supported_props
Definition: videotoolboxenc.c:248
AV_PROFILE_H264_CONSTRAINED_BASELINE
#define AV_PROFILE_H264_CONSTRAINED_BASELINE
Definition: defs.h:111
copy_param_sets
static int copy_param_sets(AVCodecContext *avctx, CMVideoFormatDescriptionRef vid_fmt, uint8_t *dst, size_t dst_size)
Definition: videotoolboxenc.c:625
H264_NAL_PPS
@ H264_NAL_PPS
Definition: h264.h:42
pthread_cond_wait
static av_always_inline int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex)
Definition: os2threads.h:192
AV_PIX_FMT_P010
#define AV_PIX_FMT_P010
Definition: pixfmt.h:581
desc
const char * desc
Definition: libsvtav1.c:79
AVMEDIA_TYPE_VIDEO
@ AVMEDIA_TYPE_VIDEO
Definition: avutil.h:201
OFFSET
#define OFFSET(x)
Definition: videotoolboxenc.c:2928
kVTProfileLevel_H264_Extended_5_0
CFStringRef kVTProfileLevel_H264_Extended_5_0
Definition: videotoolboxenc.c:116
mem.h
AVCodecContext::max_b_frames
int max_b_frames
maximum number of B-frames between non-B-frames Note: The output will be delayed by max_b_frames+1 re...
Definition: avcodec.h:809
kVTProfileLevel_H264_High_5_1
CFStringRef kVTProfileLevel_H264_High_5_1
Definition: videotoolboxenc.c:113
vtenc_send_frame
static int vtenc_send_frame(AVCodecContext *avctx, VTEncContext *vtctx, const AVFrame *frame)
Definition: videotoolboxenc.c:2602
AVBufferRef
A reference to a data buffer.
Definition: buffer.h:82
VE
#define VE
Definition: videotoolboxenc.c:2901
kVTProfileLevel_H264_High_4_1
CFStringRef kVTProfileLevel_H264_High_4_1
Definition: videotoolboxenc.c:111
AV_PIX_FMT_P010LE
@ AV_PIX_FMT_P010LE
like NV12, with 10bpp per component, data in the high bits, zeros in the low bits,...
Definition: pixfmt.h:307
AVFrameSideData
Structure to hold side data for an AVFrame.
Definition: frame.h:265
AVPixFmtDescriptor
Descriptor that unambiguously describes how the bits of a pixel are stored in the up to 4 data planes...
Definition: pixdesc.h:69
av_free
#define av_free(p)
Definition: tableprint_vlc.h:33
AVCodecContext::codec_tag
unsigned int codec_tag
fourcc (LSB first, so "ABCD" -> ('D'<<24) + ('C'<<16) + ('B'<<8) + 'A').
Definition: avcodec.h:476
VTEncContext::constant_bit_rate
int constant_bit_rate
Definition: videotoolboxenc.c:274
ff_prores_videotoolbox_encoder
const FFCodec ff_prores_videotoolbox_encoder
Definition: videotoolboxenc.c:3058
AVPacket
This structure stores compressed data.
Definition: packet.h:516
AVCodecContext::priv_data
void * priv_data
Definition: avcodec.h:478
AV_PIX_FMT_P416
#define AV_PIX_FMT_P416
Definition: pixfmt.h:600
AV_OPT_TYPE_BOOL
@ AV_OPT_TYPE_BOOL
Underlying C type is int.
Definition: opt.h:327
get_sei_msg_bytes
static int get_sei_msg_bytes(const ExtraSEI *sei, int type)
Returns a sufficient number of bytes to contain the sei data.
Definition: videotoolboxenc.c:2179
vtenc_frame
static av_cold int vtenc_frame(AVCodecContext *avctx, AVPacket *pkt, const AVFrame *frame, int *got_packet)
Definition: videotoolboxenc.c:2663
kVTProfileLevel_H264_High_3_2
CFStringRef kVTProfileLevel_H264_High_3_2
Definition: videotoolboxenc.c:109
av_freep
#define av_freep(p)
Definition: tableprint_vlc.h:34
kVTQPModulationLevel_Default
@ kVTQPModulationLevel_Default
Definition: videotoolboxenc.c:58
kVTProfileLevel_H264_High_3_0
CFStringRef kVTProfileLevel_H264_High_3_0
Definition: videotoolboxenc.c:107
VTEncContext::require_sw
int require_sw
Definition: videotoolboxenc.c:277
find_sei_end
static int find_sei_end(AVCodecContext *avctx, uint8_t *nal_data, size_t nal_size, uint8_t **sei_end)
Definition: videotoolboxenc.c:1836
av_map_videotoolbox_format_from_pixfmt2
uint32_t av_map_videotoolbox_format_from_pixfmt2(enum AVPixelFormat pix_fmt, bool full_range)
Same as av_map_videotoolbox_format_from_pixfmt function, but can map and return full range pixel form...
Definition: hwcontext_videotoolbox.c:178
AVCodecContext::width
int width
picture width / height.
Definition: avcodec.h:632
AV_PROFILE_PRORES_XQ
#define AV_PROFILE_PRORES_XQ
Definition: defs.h:186
VTEncContext::q_tail
BufNode * q_tail
Definition: videotoolboxenc.c:260
h264.h
flags
#define flags(name, subs,...)
Definition: cbs_av1.c:482
block
The exact code depends on how similar the blocks are and how related they are to the block
Definition: filter_design.txt:207
av_log
#define av_log(a,...)
Definition: tableprint_vlc.h:27
VTEncContext::codec_id
enum AVCodecID codec_id
Definition: videotoolboxenc.c:246
AVERROR_INVALIDDATA
#define AVERROR_INVALIDDATA
Invalid data found when processing input.
Definition: error.h:61
kVTCompressionPropertyKey_MaxAllowedFrameQP
CFStringRef kVTCompressionPropertyKey_MaxAllowedFrameQP
Definition: videotoolboxenc.c:138
pthread_cond_init
static av_always_inline int pthread_cond_init(pthread_cond_t *cond, const pthread_condattr_t *attr)
Definition: os2threads.h:133
VTEncContext::q_head
BufNode * q_head
Definition: videotoolboxenc.c:259
H264_NAL_SPS
@ H264_NAL_SPS
Definition: h264.h:41
AVCodecContext::sw_pix_fmt
enum AVPixelFormat sw_pix_fmt
Nominal unaccelerated pixel format, see AV_PIX_FMT_xxx.
Definition: avcodec.h:678
avstring.h
FF_QP2LAMBDA
#define FF_QP2LAMBDA
factor to convert from H.263 QP to lambda
Definition: avutil.h:227
AVColorRange
AVColorRange
Visual content value range.
Definition: pixfmt.h:711
kVTProfileLevel_H264_Main_4_2
CFStringRef kVTProfileLevel_H264_Main_4_2
Definition: videotoolboxenc.c:103
AV_OPT_TYPE_CONST
@ AV_OPT_TYPE_CONST
Special option type for declaring named constants.
Definition: opt.h:299
VT_CAVLC
@ VT_CAVLC
Definition: videotoolboxenc.c:226
PTHREAD_ONCE_INIT
#define PTHREAD_ONCE_INIT
Definition: os2threads.h:71
VTEncContext::color_primaries
CFStringRef color_primaries
Definition: videotoolboxenc.c:250
BufNode::cm_buffer
CMSampleBufferRef cm_buffer
Definition: videotoolboxenc.c:238
AVCodecContext::sample_aspect_ratio
AVRational sample_aspect_ratio
sample aspect ratio (0 if unknown) That is the width of a pixel divided by the height of the pixel.
Definition: avcodec.h:656
VTEncContext::warned_color_range
bool warned_color_range
Definition: videotoolboxenc.c:283
src
#define src
Definition: vp8dsp.c:248
get_length_code_size
static int get_length_code_size(AVCodecContext *avctx, CMSampleBufferRef sample_buffer, size_t *size)
Definition: videotoolboxenc.c:781
av_get_pix_fmt_name
const char * av_get_pix_fmt_name(enum AVPixelFormat pix_fmt)
Return the short name for a pixel format, NULL in case pix_fmt is unknown.
Definition: pixdesc.c:3233
vtenc_init
static av_cold int vtenc_init(AVCodecContext *avctx)
Definition: videotoolboxenc.c:1762
AV_CODEC_ID_PRORES
@ AV_CODEC_ID_PRORES
Definition: codec_id.h:200
kVTCompressionPropertyKey_TargetQualityForAlpha
CFStringRef kVTCompressionPropertyKey_TargetQualityForAlpha
Definition: videotoolboxenc.c:126