FFmpeg  4.4.9
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/opt.h"
28 #include "libavutil/avassert.h"
29 #include "libavutil/avstring.h"
30 #include "libavcodec/avcodec.h"
31 #include "libavutil/pixdesc.h"
32 #include "internal.h"
33 #include <pthread.h>
34 #include "atsc_a53.h"
35 #include "h264.h"
36 #include "h264_sei.h"
37 #include <dlfcn.h>
38 
39 #if !HAVE_KCMVIDEOCODECTYPE_HEVC
40 enum { kCMVideoCodecType_HEVC = 'hvc1' };
41 #endif
42 
43 #if !HAVE_KCMVIDEOCODECTYPE_HEVCWITHALPHA
45 #endif
46 
47 #if !HAVE_KCVPIXELFORMATTYPE_420YPCBCR10BIPLANARVIDEORANGE
50 #endif
51 
52 #ifndef TARGET_CPU_ARM64
53 # define TARGET_CPU_ARM64 0
54 #endif
55 
56 typedef OSStatus (*getParameterSetAtIndex)(CMFormatDescriptionRef videoDesc,
57  size_t parameterSetIndex,
58  const uint8_t **parameterSetPointerOut,
59  size_t *parameterSetSizeOut,
60  size_t *parameterSetCountOut,
61  int *NALUnitHeaderLengthOut);
62 
63 //These symbols may not be present
64 static struct{
68 
72 
94 
97 
100 
103 
106 
107 #define GET_SYM(symbol, defaultVal) \
108 do{ \
109  CFStringRef* handle = (CFStringRef*)dlsym(RTLD_DEFAULT, #symbol); \
110  if(!handle) \
111  compat_keys.symbol = CFSTR(defaultVal); \
112  else \
113  compat_keys.symbol = *handle; \
114 }while(0)
115 
117 
118 static void loadVTEncSymbols(){
119  compat_keys.CMVideoFormatDescriptionGetHEVCParameterSetAtIndex =
120  (getParameterSetAtIndex)dlsym(
121  RTLD_DEFAULT,
122  "CMVideoFormatDescriptionGetHEVCParameterSetAtIndex"
123  );
124 
128 
132 
133  GET_SYM(kVTProfileLevel_H264_Baseline_4_0, "H264_Baseline_4_0");
134  GET_SYM(kVTProfileLevel_H264_Baseline_4_2, "H264_Baseline_4_2");
135  GET_SYM(kVTProfileLevel_H264_Baseline_5_0, "H264_Baseline_5_0");
136  GET_SYM(kVTProfileLevel_H264_Baseline_5_1, "H264_Baseline_5_1");
137  GET_SYM(kVTProfileLevel_H264_Baseline_5_2, "H264_Baseline_5_2");
138  GET_SYM(kVTProfileLevel_H264_Baseline_AutoLevel, "H264_Baseline_AutoLevel");
139  GET_SYM(kVTProfileLevel_H264_Main_4_2, "H264_Main_4_2");
140  GET_SYM(kVTProfileLevel_H264_Main_5_1, "H264_Main_5_1");
141  GET_SYM(kVTProfileLevel_H264_Main_5_2, "H264_Main_5_2");
142  GET_SYM(kVTProfileLevel_H264_Main_AutoLevel, "H264_Main_AutoLevel");
143  GET_SYM(kVTProfileLevel_H264_High_3_0, "H264_High_3_0");
144  GET_SYM(kVTProfileLevel_H264_High_3_1, "H264_High_3_1");
145  GET_SYM(kVTProfileLevel_H264_High_3_2, "H264_High_3_2");
146  GET_SYM(kVTProfileLevel_H264_High_4_0, "H264_High_4_0");
147  GET_SYM(kVTProfileLevel_H264_High_4_1, "H264_High_4_1");
148  GET_SYM(kVTProfileLevel_H264_High_4_2, "H264_High_4_2");
149  GET_SYM(kVTProfileLevel_H264_High_5_1, "H264_High_5_1");
150  GET_SYM(kVTProfileLevel_H264_High_5_2, "H264_High_5_2");
151  GET_SYM(kVTProfileLevel_H264_High_AutoLevel, "H264_High_AutoLevel");
152  GET_SYM(kVTProfileLevel_H264_Extended_5_0, "H264_Extended_5_0");
153  GET_SYM(kVTProfileLevel_H264_Extended_AutoLevel, "H264_Extended_AutoLevel");
154 
155  GET_SYM(kVTProfileLevel_HEVC_Main_AutoLevel, "HEVC_Main_AutoLevel");
156  GET_SYM(kVTProfileLevel_HEVC_Main10_AutoLevel, "HEVC_Main10_AutoLevel");
157 
160  "TargetQualityForAlpha");
161 
163  "EnableHardwareAcceleratedVideoEncoder");
165  "RequireHardwareAcceleratedVideoEncoder");
166 }
167 
168 typedef enum VT_H264Profile {
176 
177 typedef enum VTH264Entropy{
180  VT_CABAC
182 
183 typedef enum VT_HEVCProfile {
189 
190 static const uint8_t start_code[] = { 0, 0, 0, 1 };
191 
192 typedef struct ExtraSEI {
193  void *data;
194  size_t size;
195 } ExtraSEI;
196 
197 typedef struct BufNode {
198  CMSampleBufferRef cm_buffer;
200  struct BufNode* next;
201  int error;
202 } BufNode;
203 
204 typedef struct VTEncContext {
205  AVClass *class;
206  enum AVCodecID codec_id;
207  VTCompressionSessionRef session;
208  CFStringRef ycbcr_matrix;
209  CFStringRef color_primaries;
210  CFStringRef transfer_function;
212 
215 
217 
220 
223 
226 
233 
237 
238  bool flushing;
241 
242  /* can't be bool type since AVOption will access it as int */
243  int a53_cc;
244 } VTEncContext;
245 
246 static int vtenc_populate_extradata(AVCodecContext *avctx,
247  CMVideoCodecType codec_type,
248  CFStringRef profile_level,
249  CFNumberRef gamma_level,
250  CFDictionaryRef enc_info,
251  CFDictionaryRef pixel_buffer_info);
252 
253 /**
254  * NULL-safe release of *refPtr, and sets value to NULL.
255  */
256 static void vt_release_num(CFNumberRef* refPtr){
257  if (!*refPtr) {
258  return;
259  }
260 
261  CFRelease(*refPtr);
262  *refPtr = NULL;
263 }
264 
265 static void set_async_error(VTEncContext *vtctx, int err)
266 {
267  BufNode *info;
268 
269  pthread_mutex_lock(&vtctx->lock);
270 
271  vtctx->async_error = err;
272 
273  info = vtctx->q_head;
274  vtctx->q_head = vtctx->q_tail = NULL;
275 
276  while (info) {
277  BufNode *next = info->next;
278  CFRelease(info->cm_buffer);
279  av_free(info);
280  info = next;
281  }
282 
283  pthread_mutex_unlock(&vtctx->lock);
284 }
285 
286 static void clear_frame_queue(VTEncContext *vtctx)
287 {
288  set_async_error(vtctx, 0);
289 }
290 
291 static int vtenc_q_pop(VTEncContext *vtctx, bool wait, CMSampleBufferRef *buf, ExtraSEI **sei)
292 {
293  BufNode *info;
294 
295  pthread_mutex_lock(&vtctx->lock);
296 
297  if (vtctx->async_error) {
298  pthread_mutex_unlock(&vtctx->lock);
299  return vtctx->async_error;
300  }
301 
302  if (vtctx->flushing && vtctx->frame_ct_in == vtctx->frame_ct_out) {
303  *buf = NULL;
304 
305  pthread_mutex_unlock(&vtctx->lock);
306  return 0;
307  }
308 
309  while (!vtctx->q_head && !vtctx->async_error && wait && !vtctx->flushing) {
310  pthread_cond_wait(&vtctx->cv_sample_sent, &vtctx->lock);
311  }
312 
313  if (!vtctx->q_head) {
314  pthread_mutex_unlock(&vtctx->lock);
315  *buf = NULL;
316  return 0;
317  }
318 
319  info = vtctx->q_head;
320  vtctx->q_head = vtctx->q_head->next;
321  if (!vtctx->q_head) {
322  vtctx->q_tail = NULL;
323  }
324 
325  vtctx->frame_ct_out++;
326  pthread_mutex_unlock(&vtctx->lock);
327 
328  *buf = info->cm_buffer;
329  if (sei && *buf) {
330  *sei = info->sei;
331  } else if (info->sei) {
332  if (info->sei->data) av_free(info->sei->data);
333  av_free(info->sei);
334  }
335  av_free(info);
336 
337 
338  return 0;
339 }
340 
341 static void vtenc_q_push(VTEncContext *vtctx, CMSampleBufferRef buffer, ExtraSEI *sei)
342 {
343  BufNode *info = av_malloc(sizeof(BufNode));
344  if (!info) {
345  set_async_error(vtctx, AVERROR(ENOMEM));
346  return;
347  }
348 
349  CFRetain(buffer);
350  info->cm_buffer = buffer;
351  info->sei = sei;
352  info->next = NULL;
353 
354  pthread_mutex_lock(&vtctx->lock);
355 
356  if (!vtctx->q_head) {
357  vtctx->q_head = info;
358  } else {
359  vtctx->q_tail->next = info;
360  }
361 
362  vtctx->q_tail = info;
363 
365  pthread_mutex_unlock(&vtctx->lock);
366 }
367 
368 static int count_nalus(size_t length_code_size,
369  CMSampleBufferRef sample_buffer,
370  int *count)
371 {
372  size_t offset = 0;
373  int status;
374  int nalu_ct = 0;
375  uint8_t size_buf[4];
376  size_t src_size = CMSampleBufferGetTotalSampleSize(sample_buffer);
377  CMBlockBufferRef block = CMSampleBufferGetDataBuffer(sample_buffer);
378 
379  if (length_code_size > 4)
380  return AVERROR_INVALIDDATA;
381 
382  while (offset < src_size) {
383  size_t curr_src_len;
384  size_t box_len = 0;
385  size_t i;
386 
387  status = CMBlockBufferCopyDataBytes(block,
388  offset,
389  length_code_size,
390  size_buf);
391 
392  if (status != kCMBlockBufferNoErr) {
393  return AVERROR_EXTERNAL;
394  }
395 
396  for (i = 0; i < length_code_size; i++) {
397  box_len <<= 8;
398  box_len |= size_buf[i];
399  }
400 
401  curr_src_len = box_len + length_code_size;
402  offset += curr_src_len;
403 
404  nalu_ct++;
405  }
406 
407  *count = nalu_ct;
408  return 0;
409 }
410 
411 static CMVideoCodecType get_cm_codec_type(enum AVCodecID id,
412  enum AVPixelFormat fmt,
413  double alpha_quality)
414 {
415  switch (id) {
416  case AV_CODEC_ID_H264: return kCMVideoCodecType_H264;
417  case AV_CODEC_ID_HEVC:
418  if (fmt == AV_PIX_FMT_BGRA && alpha_quality > 0.0) {
420  }
421  return kCMVideoCodecType_HEVC;
422  default: return 0;
423  }
424 }
425 
426 /**
427  * Get the parameter sets from a CMSampleBufferRef.
428  * @param dst If *dst isn't NULL, the parameters are copied into existing
429  * memory. *dst_size must be set accordingly when *dst != NULL.
430  * If *dst is NULL, it will be allocated.
431  * In all cases, *dst_size is set to the number of bytes used starting
432  * at *dst.
433  */
434 static int get_params_size(
435  AVCodecContext *avctx,
436  CMVideoFormatDescriptionRef vid_fmt,
437  size_t *size)
438 {
439  VTEncContext *vtctx = avctx->priv_data;
440  size_t total_size = 0;
441  size_t ps_count;
442  int is_count_bad = 0;
443  size_t i;
444  int status;
445  status = vtctx->get_param_set_func(vid_fmt,
446  0,
447  NULL,
448  NULL,
449  &ps_count,
450  NULL);
451  if (status) {
452  is_count_bad = 1;
453  ps_count = 0;
454  status = 0;
455  }
456 
457  for (i = 0; i < ps_count || is_count_bad; i++) {
458  const uint8_t *ps;
459  size_t ps_size;
460  status = vtctx->get_param_set_func(vid_fmt,
461  i,
462  &ps,
463  &ps_size,
464  NULL,
465  NULL);
466  if (status) {
467  /*
468  * When ps_count is invalid, status != 0 ends the loop normally
469  * unless we didn't get any parameter sets.
470  */
471  if (i > 0 && is_count_bad) status = 0;
472 
473  break;
474  }
475 
476  total_size += ps_size + sizeof(start_code);
477  }
478 
479  if (status) {
480  av_log(avctx, AV_LOG_ERROR, "Error getting parameter set sizes: %d\n", status);
481  return AVERROR_EXTERNAL;
482  }
483 
484  *size = total_size;
485  return 0;
486 }
487 
488 static int copy_param_sets(
489  AVCodecContext *avctx,
490  CMVideoFormatDescriptionRef vid_fmt,
491  uint8_t *dst,
492  size_t dst_size)
493 {
494  VTEncContext *vtctx = avctx->priv_data;
495  size_t ps_count;
496  int is_count_bad = 0;
497  int status;
498  size_t offset = 0;
499  size_t i;
500 
501  status = vtctx->get_param_set_func(vid_fmt,
502  0,
503  NULL,
504  NULL,
505  &ps_count,
506  NULL);
507  if (status) {
508  is_count_bad = 1;
509  ps_count = 0;
510  status = 0;
511  }
512 
513 
514  for (i = 0; i < ps_count || is_count_bad; i++) {
515  const uint8_t *ps;
516  size_t ps_size;
517  size_t next_offset;
518 
519  status = vtctx->get_param_set_func(vid_fmt,
520  i,
521  &ps,
522  &ps_size,
523  NULL,
524  NULL);
525  if (status) {
526  if (i > 0 && is_count_bad) status = 0;
527 
528  break;
529  }
530 
531  next_offset = offset + sizeof(start_code) + ps_size;
532  if (dst_size < next_offset) {
533  av_log(avctx, AV_LOG_ERROR, "Error: buffer too small for parameter sets.\n");
535  }
536 
537  memcpy(dst + offset, start_code, sizeof(start_code));
538  offset += sizeof(start_code);
539 
540  memcpy(dst + offset, ps, ps_size);
541  offset = next_offset;
542  }
543 
544  if (status) {
545  av_log(avctx, AV_LOG_ERROR, "Error getting parameter set data: %d\n", status);
546  return AVERROR_EXTERNAL;
547  }
548 
549  return 0;
550 }
551 
552 static int set_extradata(AVCodecContext *avctx, CMSampleBufferRef sample_buffer)
553 {
554  CMVideoFormatDescriptionRef vid_fmt;
555  size_t total_size;
556  int status;
557 
558  vid_fmt = CMSampleBufferGetFormatDescription(sample_buffer);
559  if (!vid_fmt) {
560  av_log(avctx, AV_LOG_ERROR, "No video format.\n");
561  return AVERROR_EXTERNAL;
562  }
563 
564  status = get_params_size(avctx, vid_fmt, &total_size);
565  if (status) {
566  av_log(avctx, AV_LOG_ERROR, "Could not get parameter sets.\n");
567  return status;
568  }
569 
570  avctx->extradata = av_mallocz(total_size + AV_INPUT_BUFFER_PADDING_SIZE);
571  if (!avctx->extradata) {
572  return AVERROR(ENOMEM);
573  }
574  avctx->extradata_size = total_size;
575 
576  status = copy_param_sets(avctx, vid_fmt, avctx->extradata, total_size);
577 
578  if (status) {
579  av_log(avctx, AV_LOG_ERROR, "Could not copy param sets.\n");
580  return status;
581  }
582 
583  return 0;
584 }
585 
587  void *ctx,
588  void *sourceFrameCtx,
589  OSStatus status,
590  VTEncodeInfoFlags flags,
591  CMSampleBufferRef sample_buffer)
592 {
593  AVCodecContext *avctx = ctx;
594  VTEncContext *vtctx = avctx->priv_data;
595  ExtraSEI *sei = sourceFrameCtx;
596 
597  if (vtctx->async_error) {
598  return;
599  }
600 
601  if (status) {
602  av_log(avctx, AV_LOG_ERROR, "Error encoding frame: %d\n", (int)status);
604  return;
605  }
606 
607  if (!sample_buffer) {
608  return;
609  }
610 
611  if (!avctx->extradata && (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER)) {
612  int set_status = set_extradata(avctx, sample_buffer);
613  if (set_status) {
614  set_async_error(vtctx, set_status);
615  return;
616  }
617  }
618 
619  vtenc_q_push(vtctx, sample_buffer, sei);
620 }
621 
623  AVCodecContext *avctx,
624  CMSampleBufferRef sample_buffer,
625  size_t *size)
626 {
627  VTEncContext *vtctx = avctx->priv_data;
628  CMVideoFormatDescriptionRef vid_fmt;
629  int isize;
630  int status;
631 
632  vid_fmt = CMSampleBufferGetFormatDescription(sample_buffer);
633  if (!vid_fmt) {
634  av_log(avctx, AV_LOG_ERROR, "Error getting buffer format description.\n");
635  return AVERROR_EXTERNAL;
636  }
637 
638  status = vtctx->get_param_set_func(vid_fmt,
639  0,
640  NULL,
641  NULL,
642  NULL,
643  &isize);
644  if (status) {
645  av_log(avctx, AV_LOG_ERROR, "Error getting length code size: %d\n", status);
646  return AVERROR_EXTERNAL;
647  }
648 
649  *size = isize;
650  return 0;
651 }
652 
653 /*
654  * Returns true on success.
655  *
656  * If profile_level_val is NULL and this method returns true, don't specify the
657  * profile/level to the encoder.
658  */
660  CFStringRef *profile_level_val)
661 {
662  VTEncContext *vtctx = avctx->priv_data;
663  int64_t profile = vtctx->profile;
664 
665  if (profile == H264_PROF_AUTO && vtctx->level) {
666  //Need to pick a profile if level is not auto-selected.
668  }
669 
670  *profile_level_val = NULL;
671 
672  switch (profile) {
673  case H264_PROF_AUTO:
674  return true;
675 
676  case H264_PROF_BASELINE:
677  switch (vtctx->level) {
678  case 0: *profile_level_val =
679  compat_keys.kVTProfileLevel_H264_Baseline_AutoLevel; break;
680  case 13: *profile_level_val = kVTProfileLevel_H264_Baseline_1_3; break;
681  case 30: *profile_level_val = kVTProfileLevel_H264_Baseline_3_0; break;
682  case 31: *profile_level_val = kVTProfileLevel_H264_Baseline_3_1; break;
683  case 32: *profile_level_val = kVTProfileLevel_H264_Baseline_3_2; break;
684  case 40: *profile_level_val =
685  compat_keys.kVTProfileLevel_H264_Baseline_4_0; break;
686  case 41: *profile_level_val = kVTProfileLevel_H264_Baseline_4_1; break;
687  case 42: *profile_level_val =
688  compat_keys.kVTProfileLevel_H264_Baseline_4_2; break;
689  case 50: *profile_level_val =
690  compat_keys.kVTProfileLevel_H264_Baseline_5_0; break;
691  case 51: *profile_level_val =
692  compat_keys.kVTProfileLevel_H264_Baseline_5_1; break;
693  case 52: *profile_level_val =
694  compat_keys.kVTProfileLevel_H264_Baseline_5_2; break;
695  }
696  break;
697 
698  case H264_PROF_MAIN:
699  switch (vtctx->level) {
700  case 0: *profile_level_val =
701  compat_keys.kVTProfileLevel_H264_Main_AutoLevel; break;
702  case 30: *profile_level_val = kVTProfileLevel_H264_Main_3_0; break;
703  case 31: *profile_level_val = kVTProfileLevel_H264_Main_3_1; break;
704  case 32: *profile_level_val = kVTProfileLevel_H264_Main_3_2; break;
705  case 40: *profile_level_val = kVTProfileLevel_H264_Main_4_0; break;
706  case 41: *profile_level_val = kVTProfileLevel_H264_Main_4_1; break;
707  case 42: *profile_level_val =
708  compat_keys.kVTProfileLevel_H264_Main_4_2; break;
709  case 50: *profile_level_val = kVTProfileLevel_H264_Main_5_0; break;
710  case 51: *profile_level_val =
711  compat_keys.kVTProfileLevel_H264_Main_5_1; break;
712  case 52: *profile_level_val =
713  compat_keys.kVTProfileLevel_H264_Main_5_2; break;
714  }
715  break;
716 
717  case H264_PROF_HIGH:
718  switch (vtctx->level) {
719  case 0: *profile_level_val =
720  compat_keys.kVTProfileLevel_H264_High_AutoLevel; break;
721  case 30: *profile_level_val =
722  compat_keys.kVTProfileLevel_H264_High_3_0; break;
723  case 31: *profile_level_val =
724  compat_keys.kVTProfileLevel_H264_High_3_1; break;
725  case 32: *profile_level_val =
726  compat_keys.kVTProfileLevel_H264_High_3_2; break;
727  case 40: *profile_level_val =
728  compat_keys.kVTProfileLevel_H264_High_4_0; break;
729  case 41: *profile_level_val =
730  compat_keys.kVTProfileLevel_H264_High_4_1; break;
731  case 42: *profile_level_val =
732  compat_keys.kVTProfileLevel_H264_High_4_2; break;
733  case 50: *profile_level_val = kVTProfileLevel_H264_High_5_0; break;
734  case 51: *profile_level_val =
735  compat_keys.kVTProfileLevel_H264_High_5_1; break;
736  case 52: *profile_level_val =
737  compat_keys.kVTProfileLevel_H264_High_5_2; break;
738  }
739  break;
740  case H264_PROF_EXTENDED:
741  switch (vtctx->level) {
742  case 0: *profile_level_val =
743  compat_keys.kVTProfileLevel_H264_Extended_AutoLevel; break;
744  case 50: *profile_level_val =
745  compat_keys.kVTProfileLevel_H264_Extended_5_0; break;
746  }
747  break;
748  }
749 
750  if (!*profile_level_val) {
751  av_log(avctx, AV_LOG_ERROR, "Invalid Profile/Level.\n");
752  return false;
753  }
754 
755  return true;
756 }
757 
758 /*
759  * Returns true on success.
760  *
761  * If profile_level_val is NULL and this method returns true, don't specify the
762  * profile/level to the encoder.
763  */
765  CFStringRef *profile_level_val)
766 {
767  VTEncContext *vtctx = avctx->priv_data;
768  int64_t profile = vtctx->profile;
769 
770  *profile_level_val = NULL;
771 
772  switch (profile) {
773  case HEVC_PROF_AUTO:
774  return true;
775  case HEVC_PROF_MAIN:
776  *profile_level_val =
777  compat_keys.kVTProfileLevel_HEVC_Main_AutoLevel;
778  break;
779  case HEVC_PROF_MAIN10:
780  *profile_level_val =
781  compat_keys.kVTProfileLevel_HEVC_Main10_AutoLevel;
782  break;
783  }
784 
785  if (!*profile_level_val) {
786  av_log(avctx, AV_LOG_ERROR, "Invalid Profile/Level.\n");
787  return false;
788  }
789 
790  return true;
791 }
792 
794  enum AVPixelFormat fmt,
795  enum AVColorRange range,
796  int* av_pixel_format,
797  int* range_guessed)
798 {
799  if (range_guessed) *range_guessed = range != AVCOL_RANGE_MPEG &&
800  range != AVCOL_RANGE_JPEG;
801 
802  //MPEG range is used when no range is set
803  if (fmt == AV_PIX_FMT_NV12) {
804  *av_pixel_format = range == AVCOL_RANGE_JPEG ?
805  kCVPixelFormatType_420YpCbCr8BiPlanarFullRange :
806  kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange;
807  } else if (fmt == AV_PIX_FMT_YUV420P) {
808  *av_pixel_format = range == AVCOL_RANGE_JPEG ?
809  kCVPixelFormatType_420YpCbCr8PlanarFullRange :
810  kCVPixelFormatType_420YpCbCr8Planar;
811  } else if (fmt == AV_PIX_FMT_BGRA) {
812  *av_pixel_format = kCVPixelFormatType_32BGRA;
813  } else if (fmt == AV_PIX_FMT_P010LE) {
814  *av_pixel_format = range == AVCOL_RANGE_JPEG ?
817  } else {
818  return AVERROR(EINVAL);
819  }
820 
821  return 0;
822 }
823 
824 static void add_color_attr(AVCodecContext *avctx, CFMutableDictionaryRef dict) {
825  VTEncContext *vtctx = avctx->priv_data;
826 
827  if (vtctx->color_primaries) {
828  CFDictionarySetValue(dict,
829  kCVImageBufferColorPrimariesKey,
830  vtctx->color_primaries);
831  }
832 
833  if (vtctx->transfer_function) {
834  CFDictionarySetValue(dict,
835  kCVImageBufferTransferFunctionKey,
836  vtctx->transfer_function);
837  }
838 
839  if (vtctx->ycbcr_matrix) {
840  CFDictionarySetValue(dict,
841  kCVImageBufferYCbCrMatrixKey,
842  vtctx->ycbcr_matrix);
843  }
844 }
845 
847  CFMutableDictionaryRef* dict)
848 {
849  CFNumberRef cv_color_format_num = NULL;
850  CFNumberRef width_num = NULL;
851  CFNumberRef height_num = NULL;
852  CFMutableDictionaryRef pixel_buffer_info = NULL;
853  int cv_color_format;
854  int status = get_cv_pixel_format(avctx,
855  avctx->pix_fmt,
856  avctx->color_range,
857  &cv_color_format,
858  NULL);
859  if (status) return status;
860 
861  pixel_buffer_info = CFDictionaryCreateMutable(
862  kCFAllocatorDefault,
863  20,
864  &kCFCopyStringDictionaryKeyCallBacks,
865  &kCFTypeDictionaryValueCallBacks);
866 
867  if (!pixel_buffer_info) goto pbinfo_nomem;
868 
869  cv_color_format_num = CFNumberCreate(kCFAllocatorDefault,
870  kCFNumberSInt32Type,
871  &cv_color_format);
872  if (!cv_color_format_num) goto pbinfo_nomem;
873 
874  CFDictionarySetValue(pixel_buffer_info,
875  kCVPixelBufferPixelFormatTypeKey,
876  cv_color_format_num);
877  vt_release_num(&cv_color_format_num);
878 
879  width_num = CFNumberCreate(kCFAllocatorDefault,
880  kCFNumberSInt32Type,
881  &avctx->width);
882  if (!width_num) return AVERROR(ENOMEM);
883 
884  CFDictionarySetValue(pixel_buffer_info,
885  kCVPixelBufferWidthKey,
886  width_num);
887  vt_release_num(&width_num);
888 
889  height_num = CFNumberCreate(kCFAllocatorDefault,
890  kCFNumberSInt32Type,
891  &avctx->height);
892  if (!height_num) goto pbinfo_nomem;
893 
894  CFDictionarySetValue(pixel_buffer_info,
895  kCVPixelBufferHeightKey,
896  height_num);
897  vt_release_num(&height_num);
898 
899  add_color_attr(avctx, pixel_buffer_info);
900 
901  *dict = pixel_buffer_info;
902  return 0;
903 
904 pbinfo_nomem:
905  vt_release_num(&cv_color_format_num);
906  vt_release_num(&width_num);
907  vt_release_num(&height_num);
908  if (pixel_buffer_info) CFRelease(pixel_buffer_info);
909 
910  return AVERROR(ENOMEM);
911 }
912 
914  CFStringRef *primaries)
915 {
916  enum AVColorPrimaries pri = avctx->color_primaries;
917  switch (pri) {
919  *primaries = NULL;
920  break;
921 
922  case AVCOL_PRI_BT470BG:
923  *primaries = kCVImageBufferColorPrimaries_EBU_3213;
924  break;
925 
926  case AVCOL_PRI_SMPTE170M:
927  *primaries = kCVImageBufferColorPrimaries_SMPTE_C;
928  break;
929 
930  case AVCOL_PRI_BT709:
931  *primaries = kCVImageBufferColorPrimaries_ITU_R_709_2;
932  break;
933 
934  case AVCOL_PRI_BT2020:
935  *primaries = compat_keys.kCVImageBufferColorPrimaries_ITU_R_2020;
936  break;
937 
938  default:
939  av_log(avctx, AV_LOG_ERROR, "Color primaries %s is not supported.\n", av_color_primaries_name(pri));
940  *primaries = NULL;
941  return -1;
942  }
943 
944  return 0;
945 }
946 
948  CFStringRef *transfer_fnc,
949  CFNumberRef *gamma_level)
950 {
951  enum AVColorTransferCharacteristic trc = avctx->color_trc;
952  Float32 gamma;
953  *gamma_level = NULL;
954 
955  switch (trc) {
957  *transfer_fnc = NULL;
958  break;
959 
960  case AVCOL_TRC_BT709:
961  *transfer_fnc = kCVImageBufferTransferFunction_ITU_R_709_2;
962  break;
963 
964  case AVCOL_TRC_SMPTE240M:
965  *transfer_fnc = kCVImageBufferTransferFunction_SMPTE_240M_1995;
966  break;
967 
968 #if HAVE_KCVIMAGEBUFFERTRANSFERFUNCTION_SMPTE_ST_2084_PQ
969  case AVCOL_TRC_SMPTE2084:
970  *transfer_fnc = kCVImageBufferTransferFunction_SMPTE_ST_2084_PQ;
971  break;
972 #endif
973 #if HAVE_KCVIMAGEBUFFERTRANSFERFUNCTION_LINEAR
974  case AVCOL_TRC_LINEAR:
975  *transfer_fnc = kCVImageBufferTransferFunction_Linear;
976  break;
977 #endif
978 #if HAVE_KCVIMAGEBUFFERTRANSFERFUNCTION_ITU_R_2100_HLG
980  *transfer_fnc = kCVImageBufferTransferFunction_ITU_R_2100_HLG;
981  break;
982 #endif
983 
984  case AVCOL_TRC_GAMMA22:
985  gamma = 2.2;
986  *transfer_fnc = kCVImageBufferTransferFunction_UseGamma;
987  *gamma_level = CFNumberCreate(NULL, kCFNumberFloat32Type, &gamma);
988  break;
989 
990  case AVCOL_TRC_GAMMA28:
991  gamma = 2.8;
992  *transfer_fnc = kCVImageBufferTransferFunction_UseGamma;
993  *gamma_level = CFNumberCreate(NULL, kCFNumberFloat32Type, &gamma);
994  break;
995 
996  case AVCOL_TRC_BT2020_10:
997  case AVCOL_TRC_BT2020_12:
998  *transfer_fnc = compat_keys.kCVImageBufferTransferFunction_ITU_R_2020;
999  break;
1000 
1001  default:
1002  *transfer_fnc = NULL;
1003  av_log(avctx, AV_LOG_ERROR, "Transfer function %s is not supported.\n", av_color_transfer_name(trc));
1004  return -1;
1005  }
1006 
1007  return 0;
1008 }
1009 
1010 static int get_cv_ycbcr_matrix(AVCodecContext *avctx, CFStringRef *matrix) {
1011  switch(avctx->colorspace) {
1012  case AVCOL_SPC_BT709:
1013  *matrix = kCVImageBufferYCbCrMatrix_ITU_R_709_2;
1014  break;
1015 
1016  case AVCOL_SPC_UNSPECIFIED:
1017  case AVCOL_SPC_RGB:
1018  *matrix = NULL;
1019  break;
1020 
1021  case AVCOL_SPC_BT470BG:
1022  case AVCOL_SPC_SMPTE170M:
1023  *matrix = kCVImageBufferYCbCrMatrix_ITU_R_601_4;
1024  break;
1025 
1026  case AVCOL_SPC_SMPTE240M:
1027  *matrix = kCVImageBufferYCbCrMatrix_SMPTE_240M_1995;
1028  break;
1029 
1030  case AVCOL_SPC_BT2020_NCL:
1031  *matrix = compat_keys.kCVImageBufferYCbCrMatrix_ITU_R_2020;
1032  break;
1033 
1034  default:
1035  av_log(avctx, AV_LOG_ERROR, "Color space %s is not supported.\n", av_color_space_name(avctx->colorspace));
1036  return -1;
1037  }
1038 
1039  return 0;
1040 }
1041 
1042 // constant quality only on Macs with Apple Silicon
1043 static bool vtenc_qscale_enabled(void)
1044 {
1045  return !TARGET_OS_IPHONE && TARGET_CPU_ARM64;
1046 }
1047 
1049  CMVideoCodecType codec_type,
1050  CFStringRef profile_level,
1051  CFNumberRef gamma_level,
1052  CFDictionaryRef enc_info,
1053  CFDictionaryRef pixel_buffer_info,
1054  VTCompressionSessionRef *session)
1055 {
1056  VTEncContext *vtctx = avctx->priv_data;
1057  SInt32 bit_rate = avctx->bit_rate;
1058  SInt32 max_rate = avctx->rc_max_rate;
1059  CFNumberRef bit_rate_num;
1060  CFNumberRef bytes_per_second;
1061  CFNumberRef one_second;
1062  CFArrayRef data_rate_limits;
1063  int64_t bytes_per_second_value = 0;
1064  int64_t one_second_value = 0;
1065  void *nums[2];
1066 
1067  int status = VTCompressionSessionCreate(kCFAllocatorDefault,
1068  avctx->width,
1069  avctx->height,
1070  codec_type,
1071  enc_info,
1072  pixel_buffer_info,
1073  kCFAllocatorDefault,
1075  avctx,
1076  session);
1077 
1078  if (status || !vtctx->session) {
1079  av_log(avctx, AV_LOG_ERROR, "Error: cannot create compression session: %d\n", status);
1080 
1081 #if !TARGET_OS_IPHONE
1082  if (!vtctx->allow_sw) {
1083  av_log(avctx, AV_LOG_ERROR, "Try -allow_sw 1. The hardware encoder may be busy, or not supported.\n");
1084  }
1085 #endif
1086 
1087  return AVERROR_EXTERNAL;
1088  }
1089 
1090  if (avctx->flags & AV_CODEC_FLAG_QSCALE && !vtenc_qscale_enabled()) {
1091  av_log(avctx, AV_LOG_ERROR, "Error: -q:v qscale not available for encoder. Use -b:v bitrate instead.\n");
1092  return AVERROR_EXTERNAL;
1093  }
1094 
1095  if (avctx->flags & AV_CODEC_FLAG_QSCALE) {
1096  Float32 quality = fminf(avctx->global_quality / 100.0f / FF_QP2LAMBDA, 1.0f);
1097  CFNumberRef quality_num = CFNumberCreate(kCFAllocatorDefault,
1098  kCFNumberFloat32Type,
1099  &quality);
1100  if (!quality_num) return AVERROR(ENOMEM);
1101 
1102  status = VTSessionSetProperty(vtctx->session,
1103  kVTCompressionPropertyKey_Quality,
1104  quality_num);
1105  CFRelease(quality_num);
1106  } else {
1107  bit_rate_num = CFNumberCreate(kCFAllocatorDefault,
1108  kCFNumberSInt32Type,
1109  &bit_rate);
1110  if (!bit_rate_num) return AVERROR(ENOMEM);
1111 
1112  status = VTSessionSetProperty(vtctx->session,
1113  kVTCompressionPropertyKey_AverageBitRate,
1114  bit_rate_num);
1115  CFRelease(bit_rate_num);
1116  }
1117 
1118  if (status) {
1119  av_log(avctx, AV_LOG_ERROR, "Error setting bitrate property: %d\n", status);
1120  return AVERROR_EXTERNAL;
1121  }
1122 
1123  if (vtctx->codec_id == AV_CODEC_ID_H264 && max_rate > 0) {
1124  // kVTCompressionPropertyKey_DataRateLimits is not available for HEVC
1125  bytes_per_second_value = max_rate >> 3;
1126  bytes_per_second = CFNumberCreate(kCFAllocatorDefault,
1127  kCFNumberSInt64Type,
1128  &bytes_per_second_value);
1129  if (!bytes_per_second) {
1130  return AVERROR(ENOMEM);
1131  }
1132  one_second_value = 1;
1133  one_second = CFNumberCreate(kCFAllocatorDefault,
1134  kCFNumberSInt64Type,
1135  &one_second_value);
1136  if (!one_second) {
1137  CFRelease(bytes_per_second);
1138  return AVERROR(ENOMEM);
1139  }
1140  nums[0] = (void *)bytes_per_second;
1141  nums[1] = (void *)one_second;
1142  data_rate_limits = CFArrayCreate(kCFAllocatorDefault,
1143  (const void **)nums,
1144  2,
1145  &kCFTypeArrayCallBacks);
1146 
1147  if (!data_rate_limits) {
1148  CFRelease(bytes_per_second);
1149  CFRelease(one_second);
1150  return AVERROR(ENOMEM);
1151  }
1152  status = VTSessionSetProperty(vtctx->session,
1153  kVTCompressionPropertyKey_DataRateLimits,
1154  data_rate_limits);
1155 
1156  CFRelease(bytes_per_second);
1157  CFRelease(one_second);
1158  CFRelease(data_rate_limits);
1159 
1160  if (status) {
1161  av_log(avctx, AV_LOG_ERROR, "Error setting max bitrate property: %d\n", status);
1162  return AVERROR_EXTERNAL;
1163  }
1164  }
1165 
1166  if (vtctx->codec_id == AV_CODEC_ID_HEVC) {
1167  if (avctx->pix_fmt == AV_PIX_FMT_BGRA && vtctx->alpha_quality > 0.0) {
1168  CFNumberRef alpha_quality_num = CFNumberCreate(kCFAllocatorDefault,
1169  kCFNumberDoubleType,
1170  &vtctx->alpha_quality);
1171  if (!alpha_quality_num) return AVERROR(ENOMEM);
1172 
1173  status = VTSessionSetProperty(vtctx->session,
1174  compat_keys.kVTCompressionPropertyKey_TargetQualityForAlpha,
1175  alpha_quality_num);
1176  CFRelease(alpha_quality_num);
1177  }
1178  }
1179 
1180  if (profile_level) {
1181  status = VTSessionSetProperty(vtctx->session,
1182  kVTCompressionPropertyKey_ProfileLevel,
1183  profile_level);
1184  if (status) {
1185  av_log(avctx, AV_LOG_ERROR, "Error setting profile/level property: %d. Output will be encoded using a supported profile/level combination.\n", status);
1186  }
1187  }
1188 
1189  if (avctx->gop_size > 0) {
1190  CFNumberRef interval = CFNumberCreate(kCFAllocatorDefault,
1191  kCFNumberIntType,
1192  &avctx->gop_size);
1193  if (!interval) {
1194  return AVERROR(ENOMEM);
1195  }
1196 
1197  status = VTSessionSetProperty(vtctx->session,
1198  kVTCompressionPropertyKey_MaxKeyFrameInterval,
1199  interval);
1200  CFRelease(interval);
1201 
1202  if (status) {
1203  av_log(avctx, AV_LOG_ERROR, "Error setting 'max key-frame interval' property: %d\n", status);
1204  return AVERROR_EXTERNAL;
1205  }
1206  }
1207 
1208  if (vtctx->frames_before) {
1209  status = VTSessionSetProperty(vtctx->session,
1210  kVTCompressionPropertyKey_MoreFramesBeforeStart,
1211  kCFBooleanTrue);
1212 
1213  if (status == kVTPropertyNotSupportedErr) {
1214  av_log(avctx, AV_LOG_WARNING, "frames_before property is not supported on this device. Ignoring.\n");
1215  } else if (status) {
1216  av_log(avctx, AV_LOG_ERROR, "Error setting frames_before property: %d\n", status);
1217  }
1218  }
1219 
1220  if (vtctx->frames_after) {
1221  status = VTSessionSetProperty(vtctx->session,
1222  kVTCompressionPropertyKey_MoreFramesAfterEnd,
1223  kCFBooleanTrue);
1224 
1225  if (status == kVTPropertyNotSupportedErr) {
1226  av_log(avctx, AV_LOG_WARNING, "frames_after property is not supported on this device. Ignoring.\n");
1227  } else if (status) {
1228  av_log(avctx, AV_LOG_ERROR, "Error setting frames_after property: %d\n", status);
1229  }
1230  }
1231 
1232  if (avctx->sample_aspect_ratio.num != 0) {
1233  CFNumberRef num;
1234  CFNumberRef den;
1235  CFMutableDictionaryRef par;
1236  AVRational *avpar = &avctx->sample_aspect_ratio;
1237 
1238  av_reduce(&avpar->num, &avpar->den,
1239  avpar->num, avpar->den,
1240  0xFFFFFFFF);
1241 
1242  num = CFNumberCreate(kCFAllocatorDefault,
1243  kCFNumberIntType,
1244  &avpar->num);
1245 
1246  den = CFNumberCreate(kCFAllocatorDefault,
1247  kCFNumberIntType,
1248  &avpar->den);
1249 
1250 
1251 
1252  par = CFDictionaryCreateMutable(kCFAllocatorDefault,
1253  2,
1254  &kCFCopyStringDictionaryKeyCallBacks,
1255  &kCFTypeDictionaryValueCallBacks);
1256 
1257  if (!par || !num || !den) {
1258  if (par) CFRelease(par);
1259  if (num) CFRelease(num);
1260  if (den) CFRelease(den);
1261 
1262  return AVERROR(ENOMEM);
1263  }
1264 
1265  CFDictionarySetValue(
1266  par,
1267  kCMFormatDescriptionKey_PixelAspectRatioHorizontalSpacing,
1268  num);
1269 
1270  CFDictionarySetValue(
1271  par,
1272  kCMFormatDescriptionKey_PixelAspectRatioVerticalSpacing,
1273  den);
1274 
1275  status = VTSessionSetProperty(vtctx->session,
1276  kVTCompressionPropertyKey_PixelAspectRatio,
1277  par);
1278 
1279  CFRelease(par);
1280  CFRelease(num);
1281  CFRelease(den);
1282 
1283  if (status) {
1284  av_log(avctx,
1285  AV_LOG_ERROR,
1286  "Error setting pixel aspect ratio to %d:%d: %d.\n",
1287  avctx->sample_aspect_ratio.num,
1288  avctx->sample_aspect_ratio.den,
1289  status);
1290 
1291  return AVERROR_EXTERNAL;
1292  }
1293  }
1294 
1295 
1296  if (vtctx->transfer_function) {
1297  status = VTSessionSetProperty(vtctx->session,
1298  kVTCompressionPropertyKey_TransferFunction,
1299  vtctx->transfer_function);
1300 
1301  if (status) {
1302  av_log(avctx, AV_LOG_WARNING, "Could not set transfer function: %d\n", status);
1303  }
1304  }
1305 
1306 
1307  if (vtctx->ycbcr_matrix) {
1308  status = VTSessionSetProperty(vtctx->session,
1309  kVTCompressionPropertyKey_YCbCrMatrix,
1310  vtctx->ycbcr_matrix);
1311 
1312  if (status) {
1313  av_log(avctx, AV_LOG_WARNING, "Could not set ycbcr matrix: %d\n", status);
1314  }
1315  }
1316 
1317 
1318  if (vtctx->color_primaries) {
1319  status = VTSessionSetProperty(vtctx->session,
1320  kVTCompressionPropertyKey_ColorPrimaries,
1321  vtctx->color_primaries);
1322 
1323  if (status) {
1324  av_log(avctx, AV_LOG_WARNING, "Could not set color primaries: %d\n", status);
1325  }
1326  }
1327 
1328  if (gamma_level) {
1329  status = VTSessionSetProperty(vtctx->session,
1330  kCVImageBufferGammaLevelKey,
1331  gamma_level);
1332 
1333  if (status) {
1334  av_log(avctx, AV_LOG_WARNING, "Could not set gamma level: %d\n", status);
1335  }
1336  }
1337 
1338  if (!vtctx->has_b_frames) {
1339  status = VTSessionSetProperty(vtctx->session,
1340  kVTCompressionPropertyKey_AllowFrameReordering,
1341  kCFBooleanFalse);
1342 
1343  if (status) {
1344  av_log(avctx, AV_LOG_ERROR, "Error setting 'allow frame reordering' property: %d\n", status);
1345  return AVERROR_EXTERNAL;
1346  }
1347  }
1348 
1349  if (vtctx->entropy != VT_ENTROPY_NOT_SET) {
1350  CFStringRef entropy = vtctx->entropy == VT_CABAC ?
1351  compat_keys.kVTH264EntropyMode_CABAC:
1352  compat_keys.kVTH264EntropyMode_CAVLC;
1353 
1354  status = VTSessionSetProperty(vtctx->session,
1355  compat_keys.kVTCompressionPropertyKey_H264EntropyMode,
1356  entropy);
1357 
1358  if (status) {
1359  av_log(avctx, AV_LOG_ERROR, "Error setting entropy property: %d\n", status);
1360  }
1361  }
1362 
1363  if (vtctx->realtime) {
1364  status = VTSessionSetProperty(vtctx->session,
1365  compat_keys.kVTCompressionPropertyKey_RealTime,
1366  kCFBooleanTrue);
1367 
1368  if (status) {
1369  av_log(avctx, AV_LOG_ERROR, "Error setting realtime property: %d\n", status);
1370  }
1371  }
1372 
1373  status = VTCompressionSessionPrepareToEncodeFrames(vtctx->session);
1374  if (status) {
1375  av_log(avctx, AV_LOG_ERROR, "Error: cannot prepare encoder: %d\n", status);
1376  return AVERROR_EXTERNAL;
1377  }
1378 
1379  return 0;
1380 }
1381 
1383 {
1384  CFMutableDictionaryRef enc_info;
1385  CFMutableDictionaryRef pixel_buffer_info = NULL;
1386  CMVideoCodecType codec_type;
1387  VTEncContext *vtctx = avctx->priv_data;
1388  CFStringRef profile_level;
1389  CFNumberRef gamma_level = NULL;
1390  int status;
1391 
1392  codec_type = get_cm_codec_type(avctx->codec_id, avctx->pix_fmt, vtctx->alpha_quality);
1393  if (!codec_type) {
1394  av_log(avctx, AV_LOG_ERROR, "Error: no mapping for AVCodecID %d\n", avctx->codec_id);
1395  return AVERROR(EINVAL);
1396  }
1397 
1398  vtctx->codec_id = avctx->codec_id;
1399 
1400  if (vtctx->codec_id == AV_CODEC_ID_H264) {
1401  vtctx->get_param_set_func = CMVideoFormatDescriptionGetH264ParameterSetAtIndex;
1402 
1403  vtctx->has_b_frames = avctx->max_b_frames > 0;
1404  if(vtctx->has_b_frames && vtctx->profile == H264_PROF_BASELINE){
1405  av_log(avctx, AV_LOG_WARNING, "Cannot use B-frames with baseline profile. Output will not contain B-frames.\n");
1406  vtctx->has_b_frames = 0;
1407  }
1408 
1409  if (vtctx->entropy == VT_CABAC && vtctx->profile == H264_PROF_BASELINE) {
1410  av_log(avctx, AV_LOG_WARNING, "CABAC entropy requires 'main' or 'high' profile, but baseline was requested. Encode will not use CABAC entropy.\n");
1411  vtctx->entropy = VT_ENTROPY_NOT_SET;
1412  }
1413 
1414  if (!get_vt_h264_profile_level(avctx, &profile_level)) return AVERROR(EINVAL);
1415  } else {
1416  vtctx->get_param_set_func = compat_keys.CMVideoFormatDescriptionGetHEVCParameterSetAtIndex;
1417  if (!vtctx->get_param_set_func) return AVERROR(EINVAL);
1418  if (!get_vt_hevc_profile_level(avctx, &profile_level)) return AVERROR(EINVAL);
1419  // HEVC has b-byramid
1420  vtctx->has_b_frames = avctx->max_b_frames > 0 ? 2 : 0;
1421  }
1422 
1423  enc_info = CFDictionaryCreateMutable(
1424  kCFAllocatorDefault,
1425  20,
1426  &kCFCopyStringDictionaryKeyCallBacks,
1427  &kCFTypeDictionaryValueCallBacks
1428  );
1429 
1430  if (!enc_info) return AVERROR(ENOMEM);
1431 
1432 #if !TARGET_OS_IPHONE
1433  if(vtctx->require_sw) {
1434  CFDictionarySetValue(enc_info,
1435  compat_keys.kVTVideoEncoderSpecification_EnableHardwareAcceleratedVideoEncoder,
1436  kCFBooleanFalse);
1437  } else if (!vtctx->allow_sw) {
1438  CFDictionarySetValue(enc_info,
1439  compat_keys.kVTVideoEncoderSpecification_RequireHardwareAcceleratedVideoEncoder,
1440  kCFBooleanTrue);
1441  } else {
1442  CFDictionarySetValue(enc_info,
1443  compat_keys.kVTVideoEncoderSpecification_EnableHardwareAcceleratedVideoEncoder,
1444  kCFBooleanTrue);
1445  }
1446 #endif
1447 
1448  if (avctx->pix_fmt != AV_PIX_FMT_VIDEOTOOLBOX) {
1449  status = create_cv_pixel_buffer_info(avctx, &pixel_buffer_info);
1450  if (status)
1451  goto init_cleanup;
1452  }
1453 
1454  vtctx->dts_delta = vtctx->has_b_frames ? -1 : 0;
1455 
1456  get_cv_transfer_function(avctx, &vtctx->transfer_function, &gamma_level);
1457  get_cv_ycbcr_matrix(avctx, &vtctx->ycbcr_matrix);
1458  get_cv_color_primaries(avctx, &vtctx->color_primaries);
1459 
1460 
1461  if (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
1462  status = vtenc_populate_extradata(avctx,
1463  codec_type,
1464  profile_level,
1465  gamma_level,
1466  enc_info,
1467  pixel_buffer_info);
1468  if (status)
1469  goto init_cleanup;
1470  }
1471 
1472  status = vtenc_create_encoder(avctx,
1473  codec_type,
1474  profile_level,
1475  gamma_level,
1476  enc_info,
1477  pixel_buffer_info,
1478  &vtctx->session);
1479 
1480 init_cleanup:
1481  if (gamma_level)
1482  CFRelease(gamma_level);
1483 
1484  if (pixel_buffer_info)
1485  CFRelease(pixel_buffer_info);
1486 
1487  CFRelease(enc_info);
1488 
1489  return status;
1490 }
1491 
1493 {
1494  VTEncContext *vtctx = avctx->priv_data;
1495  CFBooleanRef has_b_frames_cfbool;
1496  int status;
1497 
1499 
1500  pthread_mutex_init(&vtctx->lock, NULL);
1502 
1503  vtctx->session = NULL;
1504  status = vtenc_configure_encoder(avctx);
1505  if (status) return status;
1506 
1507  status = VTSessionCopyProperty(vtctx->session,
1508  kVTCompressionPropertyKey_AllowFrameReordering,
1509  kCFAllocatorDefault,
1510  &has_b_frames_cfbool);
1511 
1512  if (!status && has_b_frames_cfbool) {
1513  //Some devices don't output B-frames for main profile, even if requested.
1514  // HEVC has b-pyramid
1515  if (CFBooleanGetValue(has_b_frames_cfbool))
1516  vtctx->has_b_frames = avctx->codec_id == AV_CODEC_ID_HEVC ? 2 : 1;
1517  else
1518  vtctx->has_b_frames = 0;
1519  CFRelease(has_b_frames_cfbool);
1520  }
1521  avctx->has_b_frames = vtctx->has_b_frames;
1522 
1523  return 0;
1524 }
1525 
1526 static void vtenc_get_frame_info(CMSampleBufferRef buffer, bool *is_key_frame)
1527 {
1528  CFArrayRef attachments;
1529  CFDictionaryRef attachment;
1530  CFBooleanRef not_sync;
1531  CFIndex len;
1532 
1533  attachments = CMSampleBufferGetSampleAttachmentsArray(buffer, false);
1534  len = !attachments ? 0 : CFArrayGetCount(attachments);
1535 
1536  if (!len) {
1537  *is_key_frame = true;
1538  return;
1539  }
1540 
1541  attachment = CFArrayGetValueAtIndex(attachments, 0);
1542 
1543  if (CFDictionaryGetValueIfPresent(attachment,
1544  kCMSampleAttachmentKey_NotSync,
1545  (const void **)&not_sync))
1546  {
1547  *is_key_frame = !CFBooleanGetValue(not_sync);
1548  } else {
1549  *is_key_frame = true;
1550  }
1551 }
1552 
1553 static int is_post_sei_nal_type(int nal_type){
1554  return nal_type != H264_NAL_SEI &&
1555  nal_type != H264_NAL_SPS &&
1556  nal_type != H264_NAL_PPS &&
1557  nal_type != H264_NAL_AUD;
1558 }
1559 
1560 /*
1561  * Finds the sei message start/size of type find_sei_type.
1562  * If more than one of that type exists, the last one is returned.
1563  */
1564 static int find_sei_end(AVCodecContext *avctx,
1565  uint8_t *nal_data,
1566  size_t nal_size,
1567  uint8_t **sei_end)
1568 {
1569  int nal_type;
1570  size_t sei_payload_size = 0;
1571  *sei_end = NULL;
1572  uint8_t *nal_start = nal_data;
1573 
1574  if (!nal_size)
1575  return 0;
1576 
1577  nal_type = *nal_data & 0x1F;
1578  if (nal_type != H264_NAL_SEI)
1579  return 0;
1580 
1581  nal_data++;
1582  nal_size--;
1583 
1584  if (nal_data[nal_size - 1] == 0x80)
1585  nal_size--;
1586 
1587  while (nal_size > 0 && *nal_data > 0) {
1588  do{
1589  nal_data++;
1590  nal_size--;
1591  } while (nal_size > 0 && *nal_data == 0xFF);
1592 
1593  if (!nal_size) {
1594  av_log(avctx, AV_LOG_ERROR, "Unexpected end of SEI NAL Unit parsing type.\n");
1595  return AVERROR_INVALIDDATA;
1596  }
1597 
1598  do{
1599  sei_payload_size += *nal_data;
1600  nal_data++;
1601  nal_size--;
1602  } while (nal_size > 0 && *nal_data == 0xFF);
1603 
1604  if (nal_size < sei_payload_size) {
1605  av_log(avctx, AV_LOG_ERROR, "Unexpected end of SEI NAL Unit parsing size.\n");
1606  return AVERROR_INVALIDDATA;
1607  }
1608 
1609  nal_data += sei_payload_size;
1610  nal_size -= sei_payload_size;
1611  }
1612 
1613  *sei_end = nal_data;
1614 
1615  return nal_data - nal_start + 1;
1616 }
1617 
1618 /**
1619  * Copies the data inserting emulation prevention bytes as needed.
1620  * Existing data in the destination can be taken into account by providing
1621  * dst with a dst_offset > 0.
1622  *
1623  * @return The number of bytes copied on success. On failure, the negative of
1624  * the number of bytes needed to copy src is returned.
1625  */
1626 static int copy_emulation_prev(const uint8_t *src,
1627  size_t src_size,
1628  uint8_t *dst,
1629  ssize_t dst_offset,
1630  size_t dst_size)
1631 {
1632  int zeros = 0;
1633  int wrote_bytes;
1634  uint8_t* dst_start;
1635  uint8_t* dst_end = dst + dst_size;
1636  const uint8_t* src_end = src + src_size;
1637  int start_at = dst_offset > 2 ? dst_offset - 2 : 0;
1638  int i;
1639  for (i = start_at; i < dst_offset && i < dst_size; i++) {
1640  if (!dst[i])
1641  zeros++;
1642  else
1643  zeros = 0;
1644  }
1645 
1646  dst += dst_offset;
1647  dst_start = dst;
1648  for (; src < src_end; src++, dst++) {
1649  if (zeros == 2) {
1650  int insert_ep3_byte = *src <= 3;
1651  if (insert_ep3_byte) {
1652  if (dst < dst_end)
1653  *dst = 3;
1654  dst++;
1655  }
1656 
1657  zeros = 0;
1658  }
1659 
1660  if (dst < dst_end)
1661  *dst = *src;
1662 
1663  if (!*src)
1664  zeros++;
1665  else
1666  zeros = 0;
1667  }
1668 
1669  wrote_bytes = dst - dst_start;
1670 
1671  if (dst > dst_end)
1672  return -wrote_bytes;
1673 
1674  return wrote_bytes;
1675 }
1676 
1677 static int write_sei(const ExtraSEI *sei,
1678  int sei_type,
1679  uint8_t *dst,
1680  size_t dst_size)
1681 {
1682  uint8_t *sei_start = dst;
1683  size_t remaining_sei_size = sei->size;
1684  size_t remaining_dst_size = dst_size;
1685  int header_bytes;
1686  int bytes_written;
1687  ssize_t offset;
1688 
1689  if (!remaining_dst_size)
1690  return AVERROR_BUFFER_TOO_SMALL;
1691 
1692  while (sei_type && remaining_dst_size != 0) {
1693  int sei_byte = sei_type > 255 ? 255 : sei_type;
1694  *dst = sei_byte;
1695 
1696  sei_type -= sei_byte;
1697  dst++;
1698  remaining_dst_size--;
1699  }
1700 
1701  if (!dst_size)
1702  return AVERROR_BUFFER_TOO_SMALL;
1703 
1704  while (remaining_sei_size && remaining_dst_size != 0) {
1705  int size_byte = remaining_sei_size > 255 ? 255 : remaining_sei_size;
1706  *dst = size_byte;
1707 
1708  remaining_sei_size -= size_byte;
1709  dst++;
1710  remaining_dst_size--;
1711  }
1712 
1713  if (remaining_dst_size < sei->size)
1714  return AVERROR_BUFFER_TOO_SMALL;
1715 
1716  header_bytes = dst - sei_start;
1717 
1718  offset = header_bytes;
1719  bytes_written = copy_emulation_prev(sei->data,
1720  sei->size,
1721  sei_start,
1722  offset,
1723  dst_size);
1724  if (bytes_written < 0)
1725  return AVERROR_BUFFER_TOO_SMALL;
1726 
1727  bytes_written += header_bytes;
1728  return bytes_written;
1729 }
1730 
1731 /**
1732  * Copies NAL units and replaces length codes with
1733  * H.264 Annex B start codes. On failure, the contents of
1734  * dst_data may have been modified.
1735  *
1736  * @param length_code_size Byte length of each length code
1737  * @param sample_buffer NAL units prefixed with length codes.
1738  * @param sei Optional A53 closed captions SEI data.
1739  * @param dst_data Must be zeroed before calling this function.
1740  * Contains the copied NAL units prefixed with
1741  * start codes when the function returns
1742  * successfully.
1743  * @param dst_size Length of dst_data
1744  * @return 0 on success
1745  * AVERROR_INVALIDDATA if length_code_size is invalid
1746  * AVERROR_BUFFER_TOO_SMALL if dst_data is too small
1747  * or if a length_code in src_data specifies data beyond
1748  * the end of its buffer.
1749  */
1751  AVCodecContext *avctx,
1752  size_t length_code_size,
1753  CMSampleBufferRef sample_buffer,
1754  ExtraSEI *sei,
1755  uint8_t *dst_data,
1756  size_t dst_size)
1757 {
1758  size_t src_size = CMSampleBufferGetTotalSampleSize(sample_buffer);
1759  size_t remaining_src_size = src_size;
1760  size_t remaining_dst_size = dst_size;
1761  size_t src_offset = 0;
1762  int wrote_sei = 0;
1763  int status;
1764  uint8_t size_buf[4];
1765  uint8_t nal_type;
1766  CMBlockBufferRef block = CMSampleBufferGetDataBuffer(sample_buffer);
1767 
1768  if (length_code_size > 4) {
1769  return AVERROR_INVALIDDATA;
1770  }
1771 
1772  while (remaining_src_size > 0) {
1773  size_t curr_src_len;
1774  size_t curr_dst_len;
1775  size_t box_len = 0;
1776  size_t i;
1777 
1778  uint8_t *dst_box;
1779 
1780  status = CMBlockBufferCopyDataBytes(block,
1781  src_offset,
1782  length_code_size,
1783  size_buf);
1784  if (status) {
1785  av_log(avctx, AV_LOG_ERROR, "Cannot copy length: %d\n", status);
1786  return AVERROR_EXTERNAL;
1787  }
1788 
1789  status = CMBlockBufferCopyDataBytes(block,
1790  src_offset + length_code_size,
1791  1,
1792  &nal_type);
1793 
1794  if (status) {
1795  av_log(avctx, AV_LOG_ERROR, "Cannot copy type: %d\n", status);
1796  return AVERROR_EXTERNAL;
1797  }
1798 
1799  nal_type &= 0x1F;
1800 
1801  for (i = 0; i < length_code_size; i++) {
1802  box_len <<= 8;
1803  box_len |= size_buf[i];
1804  }
1805 
1806  if (sei && !wrote_sei && is_post_sei_nal_type(nal_type)) {
1807  //No SEI NAL unit - insert.
1808  int wrote_bytes;
1809 
1810  memcpy(dst_data, start_code, sizeof(start_code));
1811  dst_data += sizeof(start_code);
1812  remaining_dst_size -= sizeof(start_code);
1813 
1814  *dst_data = H264_NAL_SEI;
1815  dst_data++;
1816  remaining_dst_size--;
1817 
1818  wrote_bytes = write_sei(sei,
1820  dst_data,
1821  remaining_dst_size);
1822 
1823  if (wrote_bytes < 0)
1824  return wrote_bytes;
1825 
1826  remaining_dst_size -= wrote_bytes;
1827  dst_data += wrote_bytes;
1828 
1829  if (remaining_dst_size <= 0)
1830  return AVERROR_BUFFER_TOO_SMALL;
1831 
1832  *dst_data = 0x80;
1833 
1834  dst_data++;
1835  remaining_dst_size--;
1836 
1837  wrote_sei = 1;
1838  }
1839 
1840  curr_src_len = box_len + length_code_size;
1841  curr_dst_len = box_len + sizeof(start_code);
1842 
1843  if (remaining_src_size < curr_src_len) {
1844  return AVERROR_BUFFER_TOO_SMALL;
1845  }
1846 
1847  if (remaining_dst_size < curr_dst_len) {
1848  return AVERROR_BUFFER_TOO_SMALL;
1849  }
1850 
1851  dst_box = dst_data + sizeof(start_code);
1852 
1853  memcpy(dst_data, start_code, sizeof(start_code));
1854  status = CMBlockBufferCopyDataBytes(block,
1855  src_offset + length_code_size,
1856  box_len,
1857  dst_box);
1858 
1859  if (status) {
1860  av_log(avctx, AV_LOG_ERROR, "Cannot copy data: %d\n", status);
1861  return AVERROR_EXTERNAL;
1862  }
1863 
1864  if (sei && !wrote_sei && nal_type == H264_NAL_SEI) {
1865  //Found SEI NAL unit - append.
1866  int wrote_bytes;
1867  int old_sei_length;
1868  int extra_bytes;
1869  uint8_t *new_sei;
1870  old_sei_length = find_sei_end(avctx, dst_box, box_len, &new_sei);
1871  if (old_sei_length < 0)
1872  return old_sei_length;
1873 
1874  wrote_bytes = write_sei(sei,
1876  new_sei,
1877  remaining_dst_size - old_sei_length);
1878  if (wrote_bytes < 0)
1879  return wrote_bytes;
1880 
1881  if (new_sei + wrote_bytes >= dst_data + remaining_dst_size)
1882  return AVERROR_BUFFER_TOO_SMALL;
1883 
1884  new_sei[wrote_bytes++] = 0x80;
1885  extra_bytes = wrote_bytes - (dst_box + box_len - new_sei);
1886 
1887  dst_data += extra_bytes;
1888  remaining_dst_size -= extra_bytes;
1889 
1890  wrote_sei = 1;
1891  }
1892 
1893  src_offset += curr_src_len;
1894  dst_data += curr_dst_len;
1895 
1896  remaining_src_size -= curr_src_len;
1897  remaining_dst_size -= curr_dst_len;
1898  }
1899 
1900  return 0;
1901 }
1902 
1903 /**
1904  * Returns a sufficient number of bytes to contain the sei data.
1905  * It may be greater than the minimum required.
1906  */
1907 static int get_sei_msg_bytes(const ExtraSEI* sei, int type){
1908  int copied_size;
1909  if (sei->size == 0)
1910  return 0;
1911 
1912  copied_size = -copy_emulation_prev(sei->data,
1913  sei->size,
1914  NULL,
1915  0,
1916  0);
1917 
1918  if ((sei->size % 255) == 0) //may result in an extra byte
1919  copied_size++;
1920 
1921  return copied_size + sei->size / 255 + 1 + type / 255 + 1;
1922 }
1923 
1925  AVCodecContext *avctx,
1926  CMSampleBufferRef sample_buffer,
1927  AVPacket *pkt,
1928  ExtraSEI *sei)
1929 {
1930  VTEncContext *vtctx = avctx->priv_data;
1931 
1932  int status;
1933  bool is_key_frame;
1934  bool add_header;
1935  size_t length_code_size;
1936  size_t header_size = 0;
1937  size_t in_buf_size;
1938  size_t out_buf_size;
1939  size_t sei_nalu_size = 0;
1940  int64_t dts_delta;
1941  int64_t time_base_num;
1942  int nalu_count;
1943  CMTime pts;
1944  CMTime dts;
1945  CMVideoFormatDescriptionRef vid_fmt;
1946 
1947 
1948  vtenc_get_frame_info(sample_buffer, &is_key_frame);
1949  status = get_length_code_size(avctx, sample_buffer, &length_code_size);
1950  if (status) return status;
1951 
1952  add_header = is_key_frame && !(avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER);
1953 
1954  if (add_header) {
1955  vid_fmt = CMSampleBufferGetFormatDescription(sample_buffer);
1956  if (!vid_fmt) {
1957  av_log(avctx, AV_LOG_ERROR, "Cannot get format description.\n");
1958  return AVERROR_EXTERNAL;
1959  }
1960 
1961  int status = get_params_size(avctx, vid_fmt, &header_size);
1962  if (status) return status;
1963  }
1964 
1965  status = count_nalus(length_code_size, sample_buffer, &nalu_count);
1966  if(status)
1967  return status;
1968 
1969  if (sei) {
1970  size_t msg_size = get_sei_msg_bytes(sei,
1972 
1973  sei_nalu_size = sizeof(start_code) + 1 + msg_size + 1;
1974  }
1975 
1976  in_buf_size = CMSampleBufferGetTotalSampleSize(sample_buffer);
1977  out_buf_size = header_size +
1978  in_buf_size +
1979  sei_nalu_size +
1980  nalu_count * ((int)sizeof(start_code) - (int)length_code_size);
1981 
1982  status = ff_alloc_packet2(avctx, pkt, out_buf_size, out_buf_size);
1983  if (status < 0)
1984  return status;
1985 
1986  if (add_header) {
1987  status = copy_param_sets(avctx, vid_fmt, pkt->data, out_buf_size);
1988  if(status) return status;
1989  }
1990 
1991  status = copy_replace_length_codes(
1992  avctx,
1993  length_code_size,
1994  sample_buffer,
1995  sei,
1996  pkt->data + header_size,
1997  pkt->size - header_size
1998  );
1999 
2000  if (status) {
2001  av_log(avctx, AV_LOG_ERROR, "Error copying packet data: %d\n", status);
2002  return status;
2003  }
2004 
2005  if (is_key_frame) {
2007  }
2008 
2009  pts = CMSampleBufferGetPresentationTimeStamp(sample_buffer);
2010  dts = CMSampleBufferGetDecodeTimeStamp (sample_buffer);
2011 
2012  if (CMTIME_IS_INVALID(dts)) {
2013  if (!vtctx->has_b_frames) {
2014  dts = pts;
2015  } else {
2016  av_log(avctx, AV_LOG_ERROR, "DTS is invalid.\n");
2017  return AVERROR_EXTERNAL;
2018  }
2019  }
2020 
2021  dts_delta = vtctx->dts_delta >= 0 ? vtctx->dts_delta : 0;
2022  time_base_num = avctx->time_base.num;
2023  pkt->pts = pts.value / time_base_num;
2024  pkt->dts = dts.value / time_base_num - dts_delta;
2025  pkt->size = out_buf_size;
2026 
2027  return 0;
2028 }
2029 
2030 /*
2031  * contiguous_buf_size is 0 if not contiguous, and the size of the buffer
2032  * containing all planes if so.
2033  */
2035  AVCodecContext *avctx,
2036  const AVFrame *frame,
2037  int *color,
2038  int *plane_count,
2039  size_t *widths,
2040  size_t *heights,
2041  size_t *strides,
2042  size_t *contiguous_buf_size)
2043 {
2044  VTEncContext *vtctx = avctx->priv_data;
2045  int av_format = frame->format;
2046  int av_color_range = avctx->color_range;
2047  int i;
2048  int range_guessed;
2049  int status;
2050 
2051  status = get_cv_pixel_format(avctx, av_format, av_color_range, color, &range_guessed);
2052  if (status) {
2053  av_log(avctx,
2054  AV_LOG_ERROR,
2055  "Could not get pixel format for color format '%s' range '%s'.\n",
2056  av_get_pix_fmt_name(av_format),
2057  av_color_range > AVCOL_RANGE_UNSPECIFIED &&
2058  av_color_range < AVCOL_RANGE_NB ?
2059  av_color_range_name(av_color_range) :
2060  "Unknown");
2061 
2062  return AVERROR(EINVAL);
2063  }
2064 
2065  if (range_guessed) {
2066  if (!vtctx->warned_color_range) {
2067  vtctx->warned_color_range = true;
2068  av_log(avctx,
2070  "Color range not set for %s. Using MPEG range.\n",
2071  av_get_pix_fmt_name(av_format));
2072  }
2073  }
2074 
2075  switch (av_format) {
2076  case AV_PIX_FMT_NV12:
2077  *plane_count = 2;
2078 
2079  widths [0] = avctx->width;
2080  heights[0] = avctx->height;
2081  strides[0] = frame ? frame->linesize[0] : avctx->width;
2082 
2083  widths [1] = (avctx->width + 1) / 2;
2084  heights[1] = (avctx->height + 1) / 2;
2085  strides[1] = frame ? frame->linesize[1] : (avctx->width + 1) & -2;
2086  break;
2087 
2088  case AV_PIX_FMT_YUV420P:
2089  *plane_count = 3;
2090 
2091  widths [0] = avctx->width;
2092  heights[0] = avctx->height;
2093  strides[0] = frame ? frame->linesize[0] : avctx->width;
2094 
2095  widths [1] = (avctx->width + 1) / 2;
2096  heights[1] = (avctx->height + 1) / 2;
2097  strides[1] = frame ? frame->linesize[1] : (avctx->width + 1) / 2;
2098 
2099  widths [2] = (avctx->width + 1) / 2;
2100  heights[2] = (avctx->height + 1) / 2;
2101  strides[2] = frame ? frame->linesize[2] : (avctx->width + 1) / 2;
2102  break;
2103 
2104  case AV_PIX_FMT_BGRA:
2105  *plane_count = 1;
2106 
2107  widths [0] = avctx->width;
2108  heights[0] = avctx->height;
2109  strides[0] = frame ? frame->linesize[0] : avctx->width * 4;
2110  break;
2111 
2112  case AV_PIX_FMT_P010LE:
2113  *plane_count = 2;
2114  widths[0] = avctx->width;
2115  heights[0] = avctx->height;
2116  strides[0] = frame ? frame->linesize[0] : (avctx->width * 2 + 63) & -64;
2117 
2118  widths[1] = (avctx->width + 1) / 2;
2119  heights[1] = (avctx->height + 1) / 2;
2120  strides[1] = frame ? frame->linesize[1] : ((avctx->width + 1) / 2 + 63) & -64;
2121  break;
2122 
2123  default:
2124  av_log(
2125  avctx,
2126  AV_LOG_ERROR,
2127  "Could not get frame format info for color %d range %d.\n",
2128  av_format,
2129  av_color_range);
2130 
2131  return AVERROR(EINVAL);
2132  }
2133 
2134  *contiguous_buf_size = 0;
2135  for (i = 0; i < *plane_count; i++) {
2136  if (i < *plane_count - 1 &&
2137  frame->data[i] + strides[i] * heights[i] != frame->data[i + 1]) {
2138  *contiguous_buf_size = 0;
2139  break;
2140  }
2141 
2142  *contiguous_buf_size += strides[i] * heights[i];
2143  }
2144 
2145  return 0;
2146 }
2147 
2148 //Not used on OSX - frame is never copied.
2150  const AVFrame *frame,
2151  CVPixelBufferRef cv_img,
2152  const size_t *plane_strides,
2153  const size_t *plane_rows)
2154 {
2155  int i, j;
2156  size_t plane_count;
2157  int status;
2158  int rows;
2159  int src_stride;
2160  int dst_stride;
2161  uint8_t *src_addr;
2162  uint8_t *dst_addr;
2163  size_t copy_bytes;
2164 
2165  status = CVPixelBufferLockBaseAddress(cv_img, 0);
2166  if (status) {
2167  av_log(avctx, AV_LOG_ERROR, "Could not lock base address of CVPixelBuffer: %d.\n", status);
2168  return AVERROR_EXTERNAL;
2169  }
2170 
2171  if (CVPixelBufferIsPlanar(cv_img)) {
2172  plane_count = CVPixelBufferGetPlaneCount(cv_img);
2173  for (i = 0; frame->data[i]; i++) {
2174  if (i == plane_count) {
2175  CVPixelBufferUnlockBaseAddress(cv_img, 0);
2176  av_log(avctx,
2177  AV_LOG_ERROR,
2178  "Error: different number of planes in AVFrame and CVPixelBuffer.\n"
2179  );
2180 
2181  return AVERROR_EXTERNAL;
2182  }
2183 
2184  dst_addr = (uint8_t*)CVPixelBufferGetBaseAddressOfPlane(cv_img, i);
2185  src_addr = (uint8_t*)frame->data[i];
2186  dst_stride = CVPixelBufferGetBytesPerRowOfPlane(cv_img, i);
2187  src_stride = plane_strides[i];
2188  rows = plane_rows[i];
2189 
2190  if (dst_stride == src_stride) {
2191  memcpy(dst_addr, src_addr, src_stride * rows);
2192  } else {
2193  copy_bytes = dst_stride < src_stride ? dst_stride : src_stride;
2194 
2195  for (j = 0; j < rows; j++) {
2196  memcpy(dst_addr + j * dst_stride, src_addr + j * src_stride, copy_bytes);
2197  }
2198  }
2199  }
2200  } else {
2201  if (frame->data[1]) {
2202  CVPixelBufferUnlockBaseAddress(cv_img, 0);
2203  av_log(avctx,
2204  AV_LOG_ERROR,
2205  "Error: different number of planes in AVFrame and non-planar CVPixelBuffer.\n"
2206  );
2207 
2208  return AVERROR_EXTERNAL;
2209  }
2210 
2211  dst_addr = (uint8_t*)CVPixelBufferGetBaseAddress(cv_img);
2212  src_addr = (uint8_t*)frame->data[0];
2213  dst_stride = CVPixelBufferGetBytesPerRow(cv_img);
2214  src_stride = plane_strides[0];
2215  rows = plane_rows[0];
2216 
2217  if (dst_stride == src_stride) {
2218  memcpy(dst_addr, src_addr, src_stride * rows);
2219  } else {
2220  copy_bytes = dst_stride < src_stride ? dst_stride : src_stride;
2221 
2222  for (j = 0; j < rows; j++) {
2223  memcpy(dst_addr + j * dst_stride, src_addr + j * src_stride, copy_bytes);
2224  }
2225  }
2226  }
2227 
2228  status = CVPixelBufferUnlockBaseAddress(cv_img, 0);
2229  if (status) {
2230  av_log(avctx, AV_LOG_ERROR, "Could not unlock CVPixelBuffer base address: %d.\n", status);
2231  return AVERROR_EXTERNAL;
2232  }
2233 
2234  return 0;
2235 }
2236 
2238  const AVFrame *frame,
2239  CVPixelBufferRef *cv_img)
2240 {
2241  int plane_count;
2242  int color;
2243  size_t widths [AV_NUM_DATA_POINTERS];
2244  size_t heights[AV_NUM_DATA_POINTERS];
2245  size_t strides[AV_NUM_DATA_POINTERS];
2246  int status;
2247  size_t contiguous_buf_size;
2248  CVPixelBufferPoolRef pix_buf_pool;
2249  VTEncContext* vtctx = avctx->priv_data;
2250 
2251  if (avctx->pix_fmt == AV_PIX_FMT_VIDEOTOOLBOX) {
2253 
2254  *cv_img = (CVPixelBufferRef)frame->data[3];
2255  av_assert0(*cv_img);
2256 
2257  CFRetain(*cv_img);
2258  return 0;
2259  }
2260 
2261  memset(widths, 0, sizeof(widths));
2262  memset(heights, 0, sizeof(heights));
2263  memset(strides, 0, sizeof(strides));
2264 
2265  status = get_cv_pixel_info(
2266  avctx,
2267  frame,
2268  &color,
2269  &plane_count,
2270  widths,
2271  heights,
2272  strides,
2273  &contiguous_buf_size
2274  );
2275 
2276  if (status) {
2277  av_log(
2278  avctx,
2279  AV_LOG_ERROR,
2280  "Error: Cannot convert format %d color_range %d: %d\n",
2281  frame->format,
2282  frame->color_range,
2283  status
2284  );
2285 
2286  return AVERROR_EXTERNAL;
2287  }
2288 
2289  pix_buf_pool = VTCompressionSessionGetPixelBufferPool(vtctx->session);
2290  if (!pix_buf_pool) {
2291  /* On iOS, the VT session is invalidated when the APP switches from
2292  * foreground to background and vice versa. Fetch the actual error code
2293  * of the VT session to detect that case and restart the VT session
2294  * accordingly. */
2295  OSStatus vtstatus;
2296 
2297  vtstatus = VTCompressionSessionPrepareToEncodeFrames(vtctx->session);
2298  if (vtstatus == kVTInvalidSessionErr) {
2299  CFRelease(vtctx->session);
2300  vtctx->session = NULL;
2301  status = vtenc_configure_encoder(avctx);
2302  if (status == 0)
2303  pix_buf_pool = VTCompressionSessionGetPixelBufferPool(vtctx->session);
2304  }
2305  if (!pix_buf_pool) {
2306  av_log(avctx, AV_LOG_ERROR, "Could not get pixel buffer pool.\n");
2307  return AVERROR_EXTERNAL;
2308  }
2309  else
2310  av_log(avctx, AV_LOG_WARNING, "VT session restarted because of a "
2311  "kVTInvalidSessionErr error.\n");
2312  }
2313 
2314  status = CVPixelBufferPoolCreatePixelBuffer(NULL,
2315  pix_buf_pool,
2316  cv_img);
2317 
2318 
2319  if (status) {
2320  av_log(avctx, AV_LOG_ERROR, "Could not create pixel buffer from pool: %d.\n", status);
2321  return AVERROR_EXTERNAL;
2322  }
2323 
2324  status = copy_avframe_to_pixel_buffer(avctx, frame, *cv_img, strides, heights);
2325  if (status) {
2326  CFRelease(*cv_img);
2327  *cv_img = NULL;
2328  return status;
2329  }
2330 
2331  return 0;
2332 }
2333 
2335  CFDictionaryRef* dict_out)
2336 {
2337  CFDictionaryRef dict = NULL;
2338  if (frame->pict_type == AV_PICTURE_TYPE_I) {
2339  const void *keys[] = { kVTEncodeFrameOptionKey_ForceKeyFrame };
2340  const void *vals[] = { kCFBooleanTrue };
2341 
2342  dict = CFDictionaryCreate(NULL, keys, vals, 1, NULL, NULL);
2343  if(!dict) return AVERROR(ENOMEM);
2344  }
2345 
2346  *dict_out = dict;
2347  return 0;
2348 }
2349 
2351  VTEncContext *vtctx,
2352  const AVFrame *frame)
2353 {
2354  CMTime time;
2355  CFDictionaryRef frame_dict;
2356  CVPixelBufferRef cv_img = NULL;
2357  AVFrameSideData *side_data = NULL;
2358  ExtraSEI *sei = NULL;
2359  int status = create_cv_pixel_buffer(avctx, frame, &cv_img);
2360 
2361  if (status) return status;
2362 
2363  status = create_encoder_dict_h264(frame, &frame_dict);
2364  if (status) {
2365  CFRelease(cv_img);
2366  return status;
2367  }
2368 
2370  if (vtctx->a53_cc && side_data && side_data->size) {
2371  sei = av_mallocz(sizeof(*sei));
2372  if (!sei) {
2373  av_log(avctx, AV_LOG_ERROR, "Not enough memory for closed captions, skipping\n");
2374  } else {
2375  int ret = ff_alloc_a53_sei(frame, 0, &sei->data, &sei->size);
2376  if (ret < 0) {
2377  av_log(avctx, AV_LOG_ERROR, "Not enough memory for closed captions, skipping\n");
2378  av_free(sei);
2379  sei = NULL;
2380  }
2381  }
2382  }
2383 
2384  time = CMTimeMake(frame->pts * avctx->time_base.num, avctx->time_base.den);
2385  status = VTCompressionSessionEncodeFrame(
2386  vtctx->session,
2387  cv_img,
2388  time,
2389  kCMTimeInvalid,
2390  frame_dict,
2391  sei,
2392  NULL
2393  );
2394 
2395  if (frame_dict) CFRelease(frame_dict);
2396  CFRelease(cv_img);
2397 
2398  if (status) {
2399  av_log(avctx, AV_LOG_ERROR, "Error: cannot encode frame: %d\n", status);
2400  return AVERROR_EXTERNAL;
2401  }
2402 
2403  return 0;
2404 }
2405 
2407  AVCodecContext *avctx,
2408  AVPacket *pkt,
2409  const AVFrame *frame,
2410  int *got_packet)
2411 {
2412  VTEncContext *vtctx = avctx->priv_data;
2413  bool get_frame;
2414  int status;
2415  CMSampleBufferRef buf = NULL;
2416  ExtraSEI *sei = NULL;
2417 
2418  if (frame) {
2419  status = vtenc_send_frame(avctx, vtctx, frame);
2420 
2421  if (status) {
2422  status = AVERROR_EXTERNAL;
2423  goto end_nopkt;
2424  }
2425 
2426  if (vtctx->frame_ct_in == 0) {
2427  vtctx->first_pts = frame->pts;
2428  } else if(vtctx->frame_ct_in == vtctx->has_b_frames) {
2429  vtctx->dts_delta = frame->pts - vtctx->first_pts;
2430  }
2431 
2432  vtctx->frame_ct_in++;
2433  } else if(!vtctx->flushing) {
2434  vtctx->flushing = true;
2435 
2436  status = VTCompressionSessionCompleteFrames(vtctx->session,
2437  kCMTimeIndefinite);
2438 
2439  if (status) {
2440  av_log(avctx, AV_LOG_ERROR, "Error flushing frames: %d\n", status);
2441  status = AVERROR_EXTERNAL;
2442  goto end_nopkt;
2443  }
2444  }
2445 
2446  *got_packet = 0;
2447  get_frame = vtctx->dts_delta >= 0 || !frame;
2448  if (!get_frame) {
2449  status = 0;
2450  goto end_nopkt;
2451  }
2452 
2453  status = vtenc_q_pop(vtctx, !frame, &buf, &sei);
2454  if (status) goto end_nopkt;
2455  if (!buf) goto end_nopkt;
2456 
2457  status = vtenc_cm_to_avpacket(avctx, buf, pkt, sei);
2458  if (sei) {
2459  if (sei->data) av_free(sei->data);
2460  av_free(sei);
2461  }
2462  CFRelease(buf);
2463  if (status) goto end_nopkt;
2464 
2465  *got_packet = 1;
2466  return 0;
2467 
2468 end_nopkt:
2470  return status;
2471 }
2472 
2474  CMVideoCodecType codec_type,
2475  CFStringRef profile_level,
2476  CFNumberRef gamma_level,
2477  CFDictionaryRef enc_info,
2478  CFDictionaryRef pixel_buffer_info)
2479 {
2480  VTEncContext *vtctx = avctx->priv_data;
2481  int status;
2482  CVPixelBufferPoolRef pool = NULL;
2483  CVPixelBufferRef pix_buf = NULL;
2484  CMTime time;
2485  CMSampleBufferRef buf = NULL;
2486 
2487  status = vtenc_create_encoder(avctx,
2488  codec_type,
2489  profile_level,
2490  gamma_level,
2491  enc_info,
2492  pixel_buffer_info,
2493  &vtctx->session);
2494  if (status)
2495  goto pe_cleanup;
2496 
2497  pool = VTCompressionSessionGetPixelBufferPool(vtctx->session);
2498  if(!pool){
2499  av_log(avctx, AV_LOG_ERROR, "Error getting pixel buffer pool.\n");
2500  status = AVERROR_EXTERNAL;
2501  goto pe_cleanup;
2502  }
2503 
2504  status = CVPixelBufferPoolCreatePixelBuffer(NULL,
2505  pool,
2506  &pix_buf);
2507 
2508  if(status != kCVReturnSuccess){
2509  av_log(avctx, AV_LOG_ERROR, "Error creating frame from pool: %d\n", status);
2510  status = AVERROR_EXTERNAL;
2511  goto pe_cleanup;
2512  }
2513 
2514  time = CMTimeMake(0, avctx->time_base.den);
2515  status = VTCompressionSessionEncodeFrame(vtctx->session,
2516  pix_buf,
2517  time,
2518  kCMTimeInvalid,
2519  NULL,
2520  NULL,
2521  NULL);
2522 
2523  if (status) {
2524  av_log(avctx,
2525  AV_LOG_ERROR,
2526  "Error sending frame for extradata: %d\n",
2527  status);
2528  status = AVERROR_EXTERNAL;
2529  goto pe_cleanup;
2530  }
2531 
2532  //Populates extradata - output frames are flushed and param sets are available.
2533  status = VTCompressionSessionCompleteFrames(vtctx->session,
2534  kCMTimeIndefinite);
2535 
2536  if (status) {
2537  status = AVERROR_EXTERNAL;
2538  goto pe_cleanup;
2539  }
2540 
2541  status = vtenc_q_pop(vtctx, 0, &buf, NULL);
2542  if (status) {
2543  av_log(avctx, AV_LOG_ERROR, "popping: %d\n", status);
2544  goto pe_cleanup;
2545  }
2546 
2547  if (!buf) {
2548  // VideoToolbox reports a dropped frame as success with no buffer.
2549  av_log(avctx, AV_LOG_ERROR, "Extradata frame dropped, no param sets\n");
2550  status = AVERROR_EXTERNAL;
2551  goto pe_cleanup;
2552  }
2553 
2554  CFRelease(buf);
2555 
2556 pe_cleanup:
2557  CVPixelBufferRelease(pix_buf);
2558  if(vtctx->session)
2559  CFRelease(vtctx->session);
2560 
2561  vtctx->session = NULL;
2562  vtctx->frame_ct_out = 0;
2563 
2564  av_assert0(status != 0 || (avctx->extradata && avctx->extradata_size > 0));
2565 
2566  return status;
2567 }
2568 
2570 {
2571  VTEncContext *vtctx = avctx->priv_data;
2572 
2573  if(!vtctx->session) {
2575  pthread_mutex_destroy(&vtctx->lock);
2576  return 0;
2577  }
2578 
2579  VTCompressionSessionCompleteFrames(vtctx->session,
2580  kCMTimeIndefinite);
2581  clear_frame_queue(vtctx);
2583  pthread_mutex_destroy(&vtctx->lock);
2584  CFRelease(vtctx->session);
2585  vtctx->session = NULL;
2586 
2587  if (vtctx->color_primaries) {
2588  CFRelease(vtctx->color_primaries);
2589  vtctx->color_primaries = NULL;
2590  }
2591 
2592  if (vtctx->transfer_function) {
2593  CFRelease(vtctx->transfer_function);
2594  vtctx->transfer_function = NULL;
2595  }
2596 
2597  if (vtctx->ycbcr_matrix) {
2598  CFRelease(vtctx->ycbcr_matrix);
2599  vtctx->ycbcr_matrix = NULL;
2600  }
2601 
2602  return 0;
2603 }
2604 
2605 static const enum AVPixelFormat avc_pix_fmts[] = {
2610 };
2611 
2612 static const enum AVPixelFormat hevc_pix_fmts[] = {
2619 };
2620 
2621 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
2622 #define COMMON_OPTIONS \
2623  { "allow_sw", "Allow software encoding", OFFSET(allow_sw), AV_OPT_TYPE_BOOL, \
2624  { .i64 = 0 }, 0, 1, VE }, \
2625  { "require_sw", "Require software encoding", OFFSET(require_sw), AV_OPT_TYPE_BOOL, \
2626  { .i64 = 0 }, 0, 1, VE }, \
2627  { "realtime", "Hint that encoding should happen in real-time if not faster (e.g. capturing from camera).", \
2628  OFFSET(realtime), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VE }, \
2629  { "frames_before", "Other frames will come before the frames in this session. This helps smooth concatenation issues.", \
2630  OFFSET(frames_before), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VE }, \
2631  { "frames_after", "Other frames will come after the frames in this session. This helps smooth concatenation issues.", \
2632  OFFSET(frames_after), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VE },
2633 
2634 #define OFFSET(x) offsetof(VTEncContext, x)
2635 static const AVOption h264_options[] = {
2636  { "profile", "Profile", OFFSET(profile), AV_OPT_TYPE_INT, { .i64 = H264_PROF_AUTO }, H264_PROF_AUTO, H264_PROF_COUNT, VE, "profile" },
2637  { "baseline", "Baseline Profile", 0, AV_OPT_TYPE_CONST, { .i64 = H264_PROF_BASELINE }, INT_MIN, INT_MAX, VE, "profile" },
2638  { "main", "Main Profile", 0, AV_OPT_TYPE_CONST, { .i64 = H264_PROF_MAIN }, INT_MIN, INT_MAX, VE, "profile" },
2639  { "high", "High Profile", 0, AV_OPT_TYPE_CONST, { .i64 = H264_PROF_HIGH }, INT_MIN, INT_MAX, VE, "profile" },
2640  { "extended", "Extend Profile", 0, AV_OPT_TYPE_CONST, { .i64 = H264_PROF_EXTENDED }, INT_MIN, INT_MAX, VE, "profile" },
2641 
2642  { "level", "Level", OFFSET(level), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 52, VE, "level" },
2643  { "1.3", "Level 1.3, only available with Baseline Profile", 0, AV_OPT_TYPE_CONST, { .i64 = 13 }, INT_MIN, INT_MAX, VE, "level" },
2644  { "3.0", "Level 3.0", 0, AV_OPT_TYPE_CONST, { .i64 = 30 }, INT_MIN, INT_MAX, VE, "level" },
2645  { "3.1", "Level 3.1", 0, AV_OPT_TYPE_CONST, { .i64 = 31 }, INT_MIN, INT_MAX, VE, "level" },
2646  { "3.2", "Level 3.2", 0, AV_OPT_TYPE_CONST, { .i64 = 32 }, INT_MIN, INT_MAX, VE, "level" },
2647  { "4.0", "Level 4.0", 0, AV_OPT_TYPE_CONST, { .i64 = 40 }, INT_MIN, INT_MAX, VE, "level" },
2648  { "4.1", "Level 4.1", 0, AV_OPT_TYPE_CONST, { .i64 = 41 }, INT_MIN, INT_MAX, VE, "level" },
2649  { "4.2", "Level 4.2", 0, AV_OPT_TYPE_CONST, { .i64 = 42 }, INT_MIN, INT_MAX, VE, "level" },
2650  { "5.0", "Level 5.0", 0, AV_OPT_TYPE_CONST, { .i64 = 50 }, INT_MIN, INT_MAX, VE, "level" },
2651  { "5.1", "Level 5.1", 0, AV_OPT_TYPE_CONST, { .i64 = 51 }, INT_MIN, INT_MAX, VE, "level" },
2652  { "5.2", "Level 5.2", 0, AV_OPT_TYPE_CONST, { .i64 = 52 }, INT_MIN, INT_MAX, VE, "level" },
2653 
2654  { "coder", "Entropy coding", OFFSET(entropy), AV_OPT_TYPE_INT, { .i64 = VT_ENTROPY_NOT_SET }, VT_ENTROPY_NOT_SET, VT_CABAC, VE, "coder" },
2655  { "cavlc", "CAVLC entropy coding", 0, AV_OPT_TYPE_CONST, { .i64 = VT_CAVLC }, INT_MIN, INT_MAX, VE, "coder" },
2656  { "vlc", "CAVLC entropy coding", 0, AV_OPT_TYPE_CONST, { .i64 = VT_CAVLC }, INT_MIN, INT_MAX, VE, "coder" },
2657  { "cabac", "CABAC entropy coding", 0, AV_OPT_TYPE_CONST, { .i64 = VT_CABAC }, INT_MIN, INT_MAX, VE, "coder" },
2658  { "ac", "CABAC entropy coding", 0, AV_OPT_TYPE_CONST, { .i64 = VT_CABAC }, INT_MIN, INT_MAX, VE, "coder" },
2659 
2660  { "a53cc", "Use A53 Closed Captions (if available)", OFFSET(a53_cc), AV_OPT_TYPE_BOOL, {.i64 = 1}, 0, 1, VE },
2661 
2663  { NULL },
2664 };
2665 
2667  .class_name = "h264_videotoolbox",
2668  .item_name = av_default_item_name,
2669  .option = h264_options,
2670  .version = LIBAVUTIL_VERSION_INT,
2671 };
2672 
2674  .name = "h264_videotoolbox",
2675  .long_name = NULL_IF_CONFIG_SMALL("VideoToolbox H.264 Encoder"),
2676  .type = AVMEDIA_TYPE_VIDEO,
2677  .id = AV_CODEC_ID_H264,
2678  .priv_data_size = sizeof(VTEncContext),
2680  .init = vtenc_init,
2681  .encode2 = vtenc_frame,
2682  .close = vtenc_close,
2683  .capabilities = AV_CODEC_CAP_DELAY,
2684  .priv_class = &h264_videotoolbox_class,
2685  .caps_internal = FF_CODEC_CAP_INIT_THREADSAFE |
2687 };
2688 
2689 static const AVOption hevc_options[] = {
2690  { "profile", "Profile", OFFSET(profile), AV_OPT_TYPE_INT, { .i64 = HEVC_PROF_AUTO }, HEVC_PROF_AUTO, HEVC_PROF_COUNT, VE, "profile" },
2691  { "main", "Main Profile", 0, AV_OPT_TYPE_CONST, { .i64 = HEVC_PROF_MAIN }, INT_MIN, INT_MAX, VE, "profile" },
2692  { "main10", "Main10 Profile", 0, AV_OPT_TYPE_CONST, { .i64 = HEVC_PROF_MAIN10 }, INT_MIN, INT_MAX, VE, "profile" },
2693 
2694  { "alpha_quality", "Compression quality for the alpha channel", OFFSET(alpha_quality), AV_OPT_TYPE_DOUBLE, { .dbl = 0.0 }, 0.0, 1.0, VE },
2695 
2697  { NULL },
2698 };
2699 
2701  .class_name = "hevc_videotoolbox",
2702  .item_name = av_default_item_name,
2703  .option = hevc_options,
2704  .version = LIBAVUTIL_VERSION_INT,
2705 };
2706 
2708  .name = "hevc_videotoolbox",
2709  .long_name = NULL_IF_CONFIG_SMALL("VideoToolbox H.265 Encoder"),
2710  .type = AVMEDIA_TYPE_VIDEO,
2711  .id = AV_CODEC_ID_HEVC,
2712  .priv_data_size = sizeof(VTEncContext),
2714  .init = vtenc_init,
2715  .encode2 = vtenc_frame,
2716  .close = vtenc_close,
2717  .capabilities = AV_CODEC_CAP_DELAY | AV_CODEC_CAP_HARDWARE,
2718  .priv_class = &hevc_videotoolbox_class,
2719  .caps_internal = FF_CODEC_CAP_INIT_THREADSAFE |
2721  .wrapper_name = "videotoolbox",
2722 };
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:25
#define av_cold
Definition: attributes.h:88
uint8_t
simple assert() macros that are a bit more flexible than ISO C assert().
#define av_assert0(cond)
assert() equivalent, that is always enabled.
Definition: avassert.h:37
Libavcodec external API header.
static av_cold int init(AVCodecContext *avctx)
Definition: avrndec.c:31
#define flags(name, subs,...)
Definition: cbs_av1.c:572
static int FUNC() sei(CodedBitstreamContext *ctx, RWContext *rw, H264RawSEI *current)
#define NULL
Definition: coverity.c:32
long long int64_t
Definition: coverity.c:34
static AVFrame * frame
float fminf(float, float)
int ff_alloc_packet2(AVCodecContext *avctx, AVPacket *avpkt, int64_t size, int64_t min_size)
Check AVPacket size and/or allocate data.
Definition: encode.c:34
int
#define pthread_mutex_lock(a)
Definition: ffprobe.c:63
#define pthread_mutex_unlock(a)
Definition: ffprobe.c:67
#define AV_NUM_DATA_POINTERS
Definition: frame.h:319
@ AV_OPT_TYPE_CONST
Definition: opt.h:234
@ AV_OPT_TYPE_INT
Definition: opt.h:225
@ AV_OPT_TYPE_DOUBLE
Definition: opt.h:227
@ AV_OPT_TYPE_BOOL
Definition: opt.h:242
#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:77
#define AV_CODEC_FLAG_QSCALE
Use fixed qscale.
Definition: avcodec.h:275
#define AV_CODEC_FLAG_GLOBAL_HEADER
Place global headers in extradata instead of every keyframe.
Definition: avcodec.h:329
AVCodecID
Identify the syntax and semantics of the bitstream.
Definition: codec_id.h:46
#define AV_CODEC_CAP_HARDWARE
Codec is backed by a hardware implementation.
Definition: codec.h:157
@ AV_CODEC_ID_H264
Definition: codec_id.h:76
@ AV_CODEC_ID_HEVC
Definition: codec_id.h:223
#define AV_INPUT_BUFFER_PADDING_SIZE
Required number of additionally allocated bytes at the end of the input bitstream for decoding.
Definition: avcodec.h:215
void av_packet_unref(AVPacket *pkt)
Wipe the packet.
Definition: avpacket.c:634
#define AV_PKT_FLAG_KEY
The packet contains a keyframe.
Definition: packet.h:410
#define FF_QP2LAMBDA
factor to convert from H.263 QP to lambda
Definition: avutil.h:227
#define AVERROR_BUFFER_TOO_SMALL
Buffer too small.
Definition: error.h:51
#define AVERROR_EXTERNAL
Generic error in an external library.
Definition: error.h:57
#define AVERROR_INVALIDDATA
Invalid data found when processing input.
Definition: error.h:59
#define AVERROR(e)
Definition: error.h:43
AVFrameSideData * av_frame_get_side_data(const AVFrame *frame, enum AVFrameSideDataType type)
Definition: frame.c:738
@ AV_FRAME_DATA_A53_CC
ATSC A53 Part 4 Closed Captions.
Definition: frame.h:58
#define AV_LOG_WARNING
Something somehow does not look correct.
Definition: log.h:200
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition: log.h:194
const char * av_default_item_name(void *ptr)
Return the context name.
Definition: log.c:235
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
void * av_mallocz(size_t size)
Allocate a memory block with alignment suitable for all memory accesses (including vectors if availab...
Definition: mem.c:237
@ AVMEDIA_TYPE_VIDEO
Definition: avutil.h:201
@ AV_PICTURE_TYPE_I
Intra.
Definition: avutil.h:274
#define LIBAVUTIL_VERSION_INT
Definition: version.h:85
H.264 common definitions.
@ H264_NAL_PPS
Definition: h264.h:42
@ H264_NAL_SPS
Definition: h264.h:41
@ H264_NAL_SEI
Definition: h264.h:40
@ H264_NAL_AUD
Definition: h264.h:43
cl_device_type type
int i
Definition: input.c:407
#define FF_CODEC_CAP_INIT_THREADSAFE
The codec does not modify any global variables in the init function, allowing to call the init functi...
Definition: internal.h:41
#define FF_CODEC_CAP_INIT_CLEANUP
The codec allows calling the close function for deallocation even if the init function returned a fai...
Definition: internal.h:49
common internal API header
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification.
Definition: internal.h:117
static enum AVPixelFormat pix_fmts[]
Definition: libkvazaar.c:309
static const uint32_t color[16+AV_CLASS_CATEGORY_NB]
Definition: log.c:92
AVOptions.
static av_always_inline int pthread_cond_signal(pthread_cond_t *cond)
Definition: os2threads.h:152
static av_always_inline int pthread_cond_destroy(pthread_cond_t *cond)
Definition: os2threads.h:144
static av_always_inline int pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutexattr_t *attr)
Definition: os2threads.h:104
#define PTHREAD_ONCE_INIT
Definition: os2threads.h:71
static av_always_inline int pthread_cond_init(pthread_cond_t *cond, const pthread_condattr_t *attr)
Definition: os2threads.h:133
static av_always_inline int pthread_once(pthread_once_t *once_control, void(*init_routine)(void))
Definition: os2threads.h:210
_fmutex pthread_mutex_t
Definition: os2threads.h:53
static av_always_inline int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex)
Definition: os2threads.h:192
static av_always_inline int pthread_mutex_destroy(pthread_mutex_t *mutex)
Definition: os2threads.h:112
const char * av_color_transfer_name(enum AVColorTransferCharacteristic transfer)
Definition: pixdesc.c:2940
const char * av_color_range_name(enum AVColorRange range)
Definition: pixdesc.c:2901
const char * av_color_space_name(enum AVColorSpace space)
Definition: pixdesc.c:2961
const char * av_color_primaries_name(enum AVColorPrimaries primaries)
Definition: pixdesc.c:2919
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:2489
AVColorRange
Visual content value range.
Definition: pixfmt.h:551
@ AVCOL_RANGE_MPEG
Narrow or limited range content.
Definition: pixfmt.h:569
@ AVCOL_RANGE_UNSPECIFIED
Definition: pixfmt.h:552
@ AVCOL_RANGE_NB
Not part of ABI.
Definition: pixfmt.h:587
@ AVCOL_RANGE_JPEG
Full range content.
Definition: pixfmt.h:586
AVPixelFormat
Pixel format.
Definition: pixfmt.h:64
@ 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:89
@ AV_PIX_FMT_NONE
Definition: pixfmt.h:65
@ AV_PIX_FMT_P010LE
like NV12, with 10bpp per component, data in the high bits, zeros in the low bits,...
Definition: pixfmt.h:284
@ AV_PIX_FMT_VIDEOTOOLBOX
hardware decoding through Videotoolbox
Definition: pixfmt.h:282
@ AV_PIX_FMT_YUV420P
planar YUV 4:2:0, 12bpp, (1 Cr & Cb sample per 2x2 Y samples)
Definition: pixfmt.h:66
@ AV_PIX_FMT_BGRA
packed BGRA 8:8:8:8, 32bpp, BGRABGRA...
Definition: pixfmt.h:95
AVColorPrimaries
Chromaticity coordinates of the source primaries.
Definition: pixfmt.h:458
@ AVCOL_PRI_BT470BG
also ITU-R BT601-6 625 / ITU-R BT1358 625 / ITU-R BT1700 625 PAL & SECAM
Definition: pixfmt.h:465
@ AVCOL_PRI_BT709
also ITU-R BT1361 / IEC 61966-2-4 / SMPTE RP177 Annex B
Definition: pixfmt.h:460
@ AVCOL_PRI_UNSPECIFIED
Definition: pixfmt.h:461
@ AVCOL_PRI_SMPTE170M
also ITU-R BT601-6 525 / ITU-R BT1358 525 / ITU-R BT1700 NTSC
Definition: pixfmt.h:466
@ AVCOL_PRI_BT2020
ITU-R BT2020.
Definition: pixfmt.h:469
AVColorTransferCharacteristic
Color Transfer Characteristic.
Definition: pixfmt.h:483
@ AVCOL_TRC_SMPTE2084
SMPTE ST 2084 for 10-, 12-, 14- and 16-bit systems.
Definition: pixfmt.h:500
@ AVCOL_TRC_GAMMA22
also ITU-R BT470M / ITU-R BT1700 625 PAL & SECAM
Definition: pixfmt.h:488
@ AVCOL_TRC_SMPTE240M
Definition: pixfmt.h:491
@ AVCOL_TRC_LINEAR
"Linear transfer characteristics"
Definition: pixfmt.h:492
@ AVCOL_TRC_GAMMA28
also ITU-R BT470BG
Definition: pixfmt.h:489
@ AVCOL_TRC_ARIB_STD_B67
ARIB STD-B67, known as "Hybrid log-gamma".
Definition: pixfmt.h:504
@ AVCOL_TRC_BT2020_12
ITU-R BT2020 for 12-bit system.
Definition: pixfmt.h:499
@ AVCOL_TRC_BT2020_10
ITU-R BT2020 for 10-bit system.
Definition: pixfmt.h:498
@ AVCOL_TRC_UNSPECIFIED
Definition: pixfmt.h:486
@ AVCOL_TRC_BT709
also ITU-R BT1361
Definition: pixfmt.h:485
@ AVCOL_SPC_BT709
also ITU-R BT1361 / IEC 61966-2-4 xvYCC709 / SMPTE RP177 Annex B
Definition: pixfmt.h:514
@ AVCOL_SPC_BT470BG
also ITU-R BT601-6 625 / ITU-R BT1358 625 / ITU-R BT1700 625 PAL & SECAM / IEC 61966-2-4 xvYCC601
Definition: pixfmt.h:518
@ AVCOL_SPC_RGB
order of coefficients is actually GBR, also IEC 61966-2-1 (sRGB)
Definition: pixfmt.h:513
@ AVCOL_SPC_BT2020_NCL
ITU-R BT2020 non-constant luminance system.
Definition: pixfmt.h:523
@ AVCOL_SPC_UNSPECIFIED
Definition: pixfmt.h:515
@ AVCOL_SPC_SMPTE170M
also ITU-R BT601-6 525 / ITU-R BT1358 525 / ITU-R BT1700 NTSC
Definition: pixfmt.h:519
@ AVCOL_SPC_SMPTE240M
functionally identical to above
Definition: pixfmt.h:520
mfxU16 profile
Definition: qsvenc.c:45
enum AVMediaType codec_type
Definition: rtp.c:37
static char buffer[20]
Definition: seek.c:32
@ SEI_TYPE_USER_DATA_REGISTERED_ITU_T_T35
Definition: sei.h:34
Describe the class of an AVClass context structure.
Definition: log.h:67
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:72
main external API structure.
Definition: avcodec.h:536
enum AVPixelFormat pix_fmt
Pixel format, see AV_PIX_FMT_xxx.
Definition: avcodec.h:746
int width
picture width / height.
Definition: avcodec.h:709
int global_quality
Global quality for codecs which cannot change it per frame.
Definition: avcodec.h:602
enum AVColorRange color_range
MPEG vs JPEG YUV range.
Definition: avcodec.h:1171
enum AVColorPrimaries color_primaries
Chromaticity coordinates of the source primaries.
Definition: avcodec.h:1150
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:796
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:915
int has_b_frames
Size of the frame reordering buffer in the decoder.
Definition: avcodec.h:826
int64_t bit_rate
the average bitrate
Definition: avcodec.h:586
enum AVColorSpace colorspace
YUV colorspace type.
Definition: avcodec.h:1164
int gop_size
the number of pictures in a group of pictures, or 0 for intra_only
Definition: avcodec.h:731
int64_t rc_max_rate
maximum bitrate
Definition: avcodec.h:1420
enum AVColorTransferCharacteristic color_trc
Color Transfer Characteristic.
Definition: avcodec.h:1157
AVRational time_base
This is the fundamental unit of time (in seconds) in terms of which frame timestamps are represented.
Definition: avcodec.h:659
int flags
AV_CODEC_FLAG_*.
Definition: avcodec.h:616
uint8_t * extradata
some codecs need / can use extradata like Huffman tables.
Definition: avcodec.h:637
enum AVCodecID codec_id
Definition: avcodec.h:546
int extradata_size
Definition: avcodec.h:638
void * priv_data
Definition: avcodec.h:563
AVCodec.
Definition: codec.h:197
const char * name
Name of the codec implementation.
Definition: codec.h:204
Structure to hold side data for an AVFrame.
Definition: frame.h:220
This structure describes decoded (raw) audio or video data.
Definition: frame.h:318
int64_t pts
Presentation timestamp in time_base units (time when frame should be shown to user).
Definition: frame.h:411
uint8_t * data[AV_NUM_DATA_POINTERS]
pointer to the picture/channel planes.
Definition: frame.h:332
enum AVColorRange color_range
MPEG vs JPEG YUV range.
Definition: frame.h:562
int linesize[AV_NUM_DATA_POINTERS]
For video, size in bytes of each picture line.
Definition: frame.h:349
int format
format of the frame, -1 if unknown or unset Values correspond to enum AVPixelFormat for video frames,...
Definition: frame.h:391
enum AVPictureType pict_type
Picture type of the frame.
Definition: frame.h:401
AVOption.
Definition: opt.h:248
This structure stores compressed data.
Definition: packet.h:346
int flags
A combination of AV_PKT_FLAG values.
Definition: packet.h:375
int size
Definition: packet.h:370
int64_t pts
Presentation timestamp in AVStream->time_base units; the time at which the decompressed packet will b...
Definition: packet.h:362
int64_t dts
Decompression timestamp in AVStream->time_base units; the time at which the packet is decompressed.
Definition: packet.h:368
uint8_t * data
Definition: packet.h:369
Rational number (pair of numerator and denominator).
Definition: rational.h:58
int num
Numerator.
Definition: rational.h:59
int den
Denominator.
Definition: rational.h:60
CMSampleBufferRef cm_buffer
struct BufNode * next
ExtraSEI * sei
int64_t frames_before
pthread_cond_t cv_sample_sent
CFStringRef transfer_function
int64_t frame_ct_out
BufNode * q_tail
double alpha_quality
int64_t frames_after
getParameterSetAtIndex get_param_set_func
CFStringRef ycbcr_matrix
enum AVCodecID codec_id
int64_t require_sw
pthread_mutex_t lock
BufNode * q_head
VTCompressionSessionRef session
CFStringRef color_primaries
int64_t frame_ct_in
uint8_t level
Definition: svq3.c:206
#define av_free(p)
#define av_malloc(s)
#define av_log(a,...)
#define src
Definition: vp8dsp.c:255
static int16_t block[64]
Definition: dct.c:116
AVPacket * pkt
Definition: movenc.c:59
AVFormatContext * ctx
Definition: movenc.c:48
static int64_t pts
int size
static int get_frame(AVFilterContext *ctx, int is_second)
Definition: vf_nnedi.c:669
static const uint8_t offset[127][2]
Definition: vf_spp.c:107
static int write_sei(const ExtraSEI *sei, int sei_type, uint8_t *dst, size_t dst_size)
static const AVClass h264_videotoolbox_class
CFStringRef kVTVideoEncoderSpecification_EnableHardwareAcceleratedVideoEncoder
static av_cold int vtenc_init(AVCodecContext *avctx)
CFStringRef kVTProfileLevel_H264_High_4_0
static int create_encoder_dict_h264(const AVFrame *frame, CFDictionaryRef *dict_out)
CFStringRef kVTProfileLevel_H264_Main_5_2
@ kCMVideoCodecType_HEVC
static int vtenc_create_encoder(AVCodecContext *avctx, CMVideoCodecType codec_type, CFStringRef profile_level, CFNumberRef gamma_level, CFDictionaryRef enc_info, CFDictionaryRef pixel_buffer_info, VTCompressionSessionRef *session)
static int create_cv_pixel_buffer_info(AVCodecContext *avctx, CFMutableDictionaryRef *dict)
static int set_extradata(AVCodecContext *avctx, CMSampleBufferRef sample_buffer)
static CMVideoCodecType get_cm_codec_type(enum AVCodecID id, enum AVPixelFormat fmt, double alpha_quality)
CFStringRef kCVImageBufferYCbCrMatrix_ITU_R_2020
static int is_post_sei_nal_type(int nal_type)
CFStringRef kVTProfileLevel_H264_High_3_0
CFStringRef kVTProfileLevel_H264_Main_5_1
CFStringRef kVTProfileLevel_H264_Baseline_4_2
static void vtenc_output_callback(void *ctx, void *sourceFrameCtx, OSStatus status, VTEncodeInfoFlags flags, CMSampleBufferRef sample_buffer)
CFStringRef kVTProfileLevel_H264_High_4_1
static void set_async_error(VTEncContext *vtctx, int err)
static av_cold int vtenc_frame(AVCodecContext *avctx, AVPacket *pkt, const AVFrame *frame, int *got_packet)
getParameterSetAtIndex CMVideoFormatDescriptionGetHEVCParameterSetAtIndex
CFStringRef kVTCompressionPropertyKey_RealTime
#define VE
CFStringRef kVTProfileLevel_H264_Baseline_5_1
VT_HEVCProfile
@ HEVC_PROF_AUTO
@ HEVC_PROF_MAIN
@ HEVC_PROF_MAIN10
@ HEVC_PROF_COUNT
CFStringRef kVTProfileLevel_H264_High_3_1
#define COMMON_OPTIONS
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.
@ kCMVideoCodecType_HEVCWithAlpha
static int vtenc_q_pop(VTEncContext *vtctx, bool wait, CMSampleBufferRef *buf, ExtraSEI **sei)
static void add_color_attr(AVCodecContext *avctx, CFMutableDictionaryRef dict)
static void clear_frame_queue(VTEncContext *vtctx)
CFStringRef kVTH264EntropyMode_CAVLC
static pthread_once_t once_ctrl
@ kCVPixelFormatType_420YpCbCr10BiPlanarFullRange
static bool get_vt_h264_profile_level(AVCodecContext *avctx, CFStringRef *profile_level_val)
static int vtenc_send_frame(AVCodecContext *avctx, VTEncContext *vtctx, const AVFrame *frame)
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)
static const AVOption h264_options[]
CFStringRef kVTVideoEncoderSpecification_RequireHardwareAcceleratedVideoEncoder
static int get_cv_transfer_function(AVCodecContext *avctx, CFStringRef *transfer_fnc, CFNumberRef *gamma_level)
CFStringRef kVTProfileLevel_H264_Baseline_5_2
static void vt_release_num(CFNumberRef *refPtr)
NULL-safe release of *refPtr, and sets value to NULL.
static const AVOption hevc_options[]
static enum AVPixelFormat hevc_pix_fmts[]
static bool get_vt_hevc_profile_level(AVCodecContext *avctx, CFStringRef *profile_level_val)
static enum AVPixelFormat avc_pix_fmts[]
static void vtenc_get_frame_info(CMSampleBufferRef buffer, bool *is_key_frame)
static int vtenc_cm_to_avpacket(AVCodecContext *avctx, CMSampleBufferRef sample_buffer, AVPacket *pkt, ExtraSEI *sei)
CFStringRef kVTProfileLevel_H264_High_4_2
CFStringRef kVTProfileLevel_H264_High_3_2
VT_H264Profile
@ H264_PROF_EXTENDED
@ H264_PROF_COUNT
@ H264_PROF_AUTO
@ H264_PROF_HIGH
@ H264_PROF_BASELINE
@ H264_PROF_MAIN
OSStatus(* getParameterSetAtIndex)(CMFormatDescriptionRef videoDesc, size_t parameterSetIndex, const uint8_t **parameterSetPointerOut, size_t *parameterSetSizeOut, size_t *parameterSetCountOut, int *NALUnitHeaderLengthOut)
static int get_cv_color_primaries(AVCodecContext *avctx, CFStringRef *primaries)
static struct @163 compat_keys
static int find_sei_end(AVCodecContext *avctx, uint8_t *nal_data, size_t nal_size, uint8_t **sei_end)
CFStringRef kVTProfileLevel_H264_Baseline_4_0
CFStringRef kVTProfileLevel_H264_Extended_AutoLevel
CFStringRef kCVImageBufferColorPrimaries_ITU_R_2020
VTH264Entropy
@ VT_CAVLC
@ VT_ENTROPY_NOT_SET
@ VT_CABAC
static const uint8_t start_code[]
AVCodec ff_h264_videotoolbox_encoder
static int copy_param_sets(AVCodecContext *avctx, CMVideoFormatDescriptionRef vid_fmt, uint8_t *dst, size_t dst_size)
static bool vtenc_qscale_enabled(void)
CFStringRef kVTProfileLevel_HEVC_Main_AutoLevel
CFStringRef kCVImageBufferTransferFunction_ITU_R_2020
static void loadVTEncSymbols()
static int count_nalus(size_t length_code_size, CMSampleBufferRef sample_buffer, int *count)
CFStringRef kVTProfileLevel_H264_High_AutoLevel
static int get_length_code_size(AVCodecContext *avctx, CMSampleBufferRef sample_buffer, size_t *size)
static av_cold int vtenc_close(AVCodecContext *avctx)
CFStringRef kVTCompressionPropertyKey_H264EntropyMode
static int vtenc_populate_extradata(AVCodecContext *avctx, CMVideoCodecType codec_type, CFStringRef profile_level, CFNumberRef gamma_level, CFDictionaryRef enc_info, CFDictionaryRef pixel_buffer_info)
CFStringRef kVTH264EntropyMode_CABAC
CFStringRef kVTProfileLevel_H264_Main_AutoLevel
static const AVClass hevc_videotoolbox_class
static void vtenc_q_push(VTEncContext *vtctx, CMSampleBufferRef buffer, ExtraSEI *sei)
AVCodec ff_hevc_videotoolbox_encoder
#define OFFSET(x)
CFStringRef kVTCompressionPropertyKey_TargetQualityForAlpha
#define TARGET_CPU_ARM64
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.
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)
static int get_cv_pixel_format(AVCodecContext *avctx, enum AVPixelFormat fmt, enum AVColorRange range, int *av_pixel_format, int *range_guessed)
CFStringRef kVTProfileLevel_H264_High_5_2
CFStringRef kVTProfileLevel_H264_High_5_1
static int create_cv_pixel_buffer(AVCodecContext *avctx, const AVFrame *frame, CVPixelBufferRef *cv_img)
static int get_sei_msg_bytes(const ExtraSEI *sei, int type)
Returns a sufficient number of bytes to contain the sei data.
#define GET_SYM(symbol, defaultVal)
static int get_params_size(AVCodecContext *avctx, CMVideoFormatDescriptionRef vid_fmt, size_t *size)
Get the parameter sets from a CMSampleBufferRef.
CFStringRef kVTProfileLevel_HEVC_Main10_AutoLevel
static int get_cv_ycbcr_matrix(AVCodecContext *avctx, CFStringRef *matrix)
CFStringRef kVTProfileLevel_H264_Baseline_5_0
CFStringRef kVTProfileLevel_H264_Baseline_AutoLevel
static int vtenc_configure_encoder(AVCodecContext *avctx)
CFStringRef kVTProfileLevel_H264_Main_4_2
@ kCVPixelFormatType_420YpCbCr10BiPlanarVideoRange
CFStringRef kVTProfileLevel_H264_Extended_5_0
int len