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