FFmpeg
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Groups Pages
avfoundation.m
Go to the documentation of this file.
1 /*
2  * AVFoundation input device
3  * Copyright (c) 2014 Thilo Borgmann <thilo.borgmann@mail.de>
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21 
22 /**
23  * @file
24  * AVFoundation input device
25  * @author Thilo Borgmann <thilo.borgmann@mail.de>
26  */
27 
28 #import <AVFoundation/AVFoundation.h>
29 #include <pthread.h>
30 
31 #include "libavutil/pixdesc.h"
32 #include "libavutil/opt.h"
33 #include "libavutil/avstring.h"
34 #include "libavformat/internal.h"
35 #include "libavutil/internal.h"
36 #include "libavutil/parseutils.h"
37 #include "libavutil/time.h"
38 #include "libavutil/imgutils.h"
39 #include "avdevice.h"
40 
41 static const int avf_time_base = 1000000;
42 
43 static const AVRational avf_time_base_q = {
44  .num = 1,
45  .den = avf_time_base
46 };
47 
50  OSType avf_id;
51 };
52 
53 static const struct AVFPixelFormatSpec avf_pixel_formats[] = {
54  { AV_PIX_FMT_MONOBLACK, kCVPixelFormatType_1Monochrome },
55  { AV_PIX_FMT_RGB555BE, kCVPixelFormatType_16BE555 },
56  { AV_PIX_FMT_RGB555LE, kCVPixelFormatType_16LE555 },
57  { AV_PIX_FMT_RGB565BE, kCVPixelFormatType_16BE565 },
58  { AV_PIX_FMT_RGB565LE, kCVPixelFormatType_16LE565 },
59  { AV_PIX_FMT_RGB24, kCVPixelFormatType_24RGB },
60  { AV_PIX_FMT_BGR24, kCVPixelFormatType_24BGR },
61  { AV_PIX_FMT_0RGB, kCVPixelFormatType_32ARGB },
62  { AV_PIX_FMT_BGR0, kCVPixelFormatType_32BGRA },
63  { AV_PIX_FMT_0BGR, kCVPixelFormatType_32ABGR },
64  { AV_PIX_FMT_RGB0, kCVPixelFormatType_32RGBA },
65  { AV_PIX_FMT_BGR48BE, kCVPixelFormatType_48RGB },
66  { AV_PIX_FMT_UYVY422, kCVPixelFormatType_422YpCbCr8 },
67  { AV_PIX_FMT_YUVA444P, kCVPixelFormatType_4444YpCbCrA8R },
68  { AV_PIX_FMT_YUVA444P16LE, kCVPixelFormatType_4444AYpCbCr16 },
69  { AV_PIX_FMT_YUV444P, kCVPixelFormatType_444YpCbCr8 },
70  { AV_PIX_FMT_YUV422P16, kCVPixelFormatType_422YpCbCr16 },
71  { AV_PIX_FMT_YUV422P10, kCVPixelFormatType_422YpCbCr10 },
72  { AV_PIX_FMT_YUV444P10, kCVPixelFormatType_444YpCbCr10 },
73  { AV_PIX_FMT_YUV420P, kCVPixelFormatType_420YpCbCr8Planar },
74  { AV_PIX_FMT_NV12, kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange },
75  { AV_PIX_FMT_YUYV422, kCVPixelFormatType_422YpCbCr8_yuvs },
76 #if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1080
77  { AV_PIX_FMT_GRAY8, kCVPixelFormatType_OneComponent8 },
78 #endif
79  { AV_PIX_FMT_NONE, 0 }
80 };
81 
82 typedef struct
83 {
84  AVClass* class;
85 
88  int64_t first_pts;
89  int64_t first_audio_pts;
94 
96  int width, height;
97 
100 
106 
109 
111 
115  int audio_be;
119 
122 
123  enum AVPixelFormat pixel_format;
124 
125  AVCaptureSession *capture_session;
126  AVCaptureVideoDataOutput *video_output;
127  AVCaptureAudioDataOutput *audio_output;
128  CMSampleBufferRef current_frame;
129  CMSampleBufferRef current_audio_frame;
130 } AVFContext;
131 
133 {
135 }
136 
138 {
140 }
141 
142 /** FrameReciever class - delegate for AVCaptureSession
143  */
144 @interface AVFFrameReceiver : NSObject
145 {
147 }
148 
149 - (id)initWithContext:(AVFContext*)context;
150 
151 - (void) captureOutput:(AVCaptureOutput *)captureOutput
152  didOutputSampleBuffer:(CMSampleBufferRef)videoFrame
153  fromConnection:(AVCaptureConnection *)connection;
154 
155 @end
156 
157 @implementation AVFFrameReceiver
158 
159 - (id)initWithContext:(AVFContext*)context
160 {
161  if (self = [super init]) {
162  _context = context;
163  }
164  return self;
165 }
166 
167 - (void) captureOutput:(AVCaptureOutput *)captureOutput
168  didOutputSampleBuffer:(CMSampleBufferRef)videoFrame
169  fromConnection:(AVCaptureConnection *)connection
170 {
172 
173  if (_context->current_frame != nil) {
174  CFRelease(_context->current_frame);
175  }
176 
177  _context->current_frame = (CMSampleBufferRef)CFRetain(videoFrame);
178 
180 
182 
184 }
185 
186 @end
187 
188 /** AudioReciever class - delegate for AVCaptureSession
189  */
190 @interface AVFAudioReceiver : NSObject
191 {
193 }
194 
195 - (id)initWithContext:(AVFContext*)context;
196 
197 - (void) captureOutput:(AVCaptureOutput *)captureOutput
198  didOutputSampleBuffer:(CMSampleBufferRef)audioFrame
199  fromConnection:(AVCaptureConnection *)connection;
200 
201 @end
202 
203 @implementation AVFAudioReceiver
204 
205 - (id)initWithContext:(AVFContext*)context
206 {
207  if (self = [super init]) {
208  _context = context;
209  }
210  return self;
211 }
212 
213 - (void) captureOutput:(AVCaptureOutput *)captureOutput
214  didOutputSampleBuffer:(CMSampleBufferRef)audioFrame
215  fromConnection:(AVCaptureConnection *)connection
216 {
218 
219  if (_context->current_audio_frame != nil) {
220  CFRelease(_context->current_audio_frame);
221  }
222 
223  _context->current_audio_frame = (CMSampleBufferRef)CFRetain(audioFrame);
224 
226 
228 
230 }
231 
232 @end
233 
235 {
236  [ctx->capture_session stopRunning];
237 
238  [ctx->capture_session release];
239  [ctx->video_output release];
240  [ctx->audio_output release];
241  [ctx->avf_delegate release];
242  [ctx->avf_audio_delegate release];
243 
244  ctx->capture_session = NULL;
245  ctx->video_output = NULL;
246  ctx->audio_output = NULL;
247  ctx->avf_delegate = NULL;
248  ctx->avf_audio_delegate = NULL;
249 
250  av_freep(&ctx->audio_buffer);
251 
254 
255  if (ctx->current_frame) {
256  CFRelease(ctx->current_frame);
257  }
258 }
259 
261 {
263  char *tmp = av_strdup(s->url);
264  char *save;
265 
266  if (tmp[0] != ':') {
267  ctx->video_filename = av_strtok(tmp, ":", &save);
268  ctx->audio_filename = av_strtok(NULL, ":", &save);
269  } else {
270  ctx->audio_filename = av_strtok(tmp, ":", &save);
271  }
272 }
273 
274 /**
275  * Configure the video device.
276  *
277  * Configure the video device using a run-time approach to access properties
278  * since formats, activeFormat are available since iOS >= 7.0 or OSX >= 10.7
279  * and activeVideoMaxFrameDuration is available since i0S >= 7.0 and OSX >= 10.9.
280  *
281  * The NSUndefinedKeyException must be handled by the caller of this function.
282  *
283  */
284 static int configure_video_device(AVFormatContext *s, AVCaptureDevice *video_device)
285 {
287 
288  double framerate = av_q2d(ctx->framerate);
289  NSObject *range = nil;
290  NSObject *format = nil;
291  NSObject *selected_range = nil;
292  NSObject *selected_format = nil;
293 
294  for (format in [video_device valueForKey:@"formats"]) {
295  CMFormatDescriptionRef formatDescription;
296  CMVideoDimensions dimensions;
297 
298  formatDescription = (CMFormatDescriptionRef) [format performSelector:@selector(formatDescription)];
299  dimensions = CMVideoFormatDescriptionGetDimensions(formatDescription);
300 
301  if ((ctx->width == 0 && ctx->height == 0) ||
302  (dimensions.width == ctx->width && dimensions.height == ctx->height)) {
303 
304  selected_format = format;
305 
306  for (range in [format valueForKey:@"videoSupportedFrameRateRanges"]) {
307  double max_framerate;
308 
309  [[range valueForKey:@"maxFrameRate"] getValue:&max_framerate];
310  if (fabs (framerate - max_framerate) < 0.01) {
311  selected_range = range;
312  break;
313  }
314  }
315  }
316  }
317 
318  if (!selected_format) {
319  av_log(s, AV_LOG_ERROR, "Selected video size (%dx%d) is not supported by the device\n",
320  ctx->width, ctx->height);
321  goto unsupported_format;
322  }
323 
324  if (!selected_range) {
325  av_log(s, AV_LOG_ERROR, "Selected framerate (%f) is not supported by the device\n",
326  framerate);
327  goto unsupported_format;
328  }
329 
330  if ([video_device lockForConfiguration:NULL] == YES) {
331  NSValue *min_frame_duration = [selected_range valueForKey:@"minFrameDuration"];
332 
333  [video_device setValue:selected_format forKey:@"activeFormat"];
334  [video_device setValue:min_frame_duration forKey:@"activeVideoMinFrameDuration"];
335  [video_device setValue:min_frame_duration forKey:@"activeVideoMaxFrameDuration"];
336  } else {
337  av_log(s, AV_LOG_ERROR, "Could not lock device for configuration");
338  return AVERROR(EINVAL);
339  }
340 
341  return 0;
342 
343 unsupported_format:
344 
345  av_log(s, AV_LOG_ERROR, "Supported modes:\n");
346  for (format in [video_device valueForKey:@"formats"]) {
347  CMFormatDescriptionRef formatDescription;
348  CMVideoDimensions dimensions;
349 
350  formatDescription = (CMFormatDescriptionRef) [format performSelector:@selector(formatDescription)];
351  dimensions = CMVideoFormatDescriptionGetDimensions(formatDescription);
352 
353  for (range in [format valueForKey:@"videoSupportedFrameRateRanges"]) {
354  double min_framerate;
355  double max_framerate;
356 
357  [[range valueForKey:@"minFrameRate"] getValue:&min_framerate];
358  [[range valueForKey:@"maxFrameRate"] getValue:&max_framerate];
359  av_log(s, AV_LOG_ERROR, " %dx%d@[%f %f]fps\n",
360  dimensions.width, dimensions.height,
361  min_framerate, max_framerate);
362  }
363  }
364  return AVERROR(EINVAL);
365 }
366 
367 static int add_video_device(AVFormatContext *s, AVCaptureDevice *video_device)
368 {
370  int ret;
371  NSError *error = nil;
372  AVCaptureInput* capture_input = nil;
373  struct AVFPixelFormatSpec pxl_fmt_spec;
374  NSNumber *pixel_format;
375  NSDictionary *capture_dict;
376  dispatch_queue_t queue;
377 
378  if (ctx->video_device_index < ctx->num_video_devices) {
379  capture_input = (AVCaptureInput*) [[[AVCaptureDeviceInput alloc] initWithDevice:video_device error:&error] autorelease];
380  } else {
381  capture_input = (AVCaptureInput*) video_device;
382  }
383 
384  if (!capture_input) {
385  av_log(s, AV_LOG_ERROR, "Failed to create AV capture input device: %s\n",
386  [[error localizedDescription] UTF8String]);
387  return 1;
388  }
389 
390  if ([ctx->capture_session canAddInput:capture_input]) {
391  [ctx->capture_session addInput:capture_input];
392  } else {
393  av_log(s, AV_LOG_ERROR, "can't add video input to capture session\n");
394  return 1;
395  }
396 
397  // Attaching output
398  ctx->video_output = [[AVCaptureVideoDataOutput alloc] init];
399 
400  if (!ctx->video_output) {
401  av_log(s, AV_LOG_ERROR, "Failed to init AV video output\n");
402  return 1;
403  }
404 
405  // Configure device framerate and video size
406  @try {
407  if ((ret = configure_video_device(s, video_device)) < 0) {
408  return ret;
409  }
410  } @catch (NSException *exception) {
411  if (![[exception name] isEqualToString:NSUndefinedKeyException]) {
412  av_log (s, AV_LOG_ERROR, "An error occurred: %s", [exception.reason UTF8String]);
413  return AVERROR_EXTERNAL;
414  }
415  }
416 
417  // select pixel format
418  pxl_fmt_spec.ff_id = AV_PIX_FMT_NONE;
419 
420  for (int i = 0; avf_pixel_formats[i].ff_id != AV_PIX_FMT_NONE; i++) {
421  if (ctx->pixel_format == avf_pixel_formats[i].ff_id) {
422  pxl_fmt_spec = avf_pixel_formats[i];
423  break;
424  }
425  }
426 
427  // check if selected pixel format is supported by AVFoundation
428  if (pxl_fmt_spec.ff_id == AV_PIX_FMT_NONE) {
429  av_log(s, AV_LOG_ERROR, "Selected pixel format (%s) is not supported by AVFoundation.\n",
430  av_get_pix_fmt_name(pxl_fmt_spec.ff_id));
431  return 1;
432  }
433 
434  // check if the pixel format is available for this device
435  if ([[ctx->video_output availableVideoCVPixelFormatTypes] indexOfObject:[NSNumber numberWithInt:pxl_fmt_spec.avf_id]] == NSNotFound) {
436  av_log(s, AV_LOG_ERROR, "Selected pixel format (%s) is not supported by the input device.\n",
437  av_get_pix_fmt_name(pxl_fmt_spec.ff_id));
438 
439  pxl_fmt_spec.ff_id = AV_PIX_FMT_NONE;
440 
441  av_log(s, AV_LOG_ERROR, "Supported pixel formats:\n");
442  for (NSNumber *pxl_fmt in [ctx->video_output availableVideoCVPixelFormatTypes]) {
443  struct AVFPixelFormatSpec pxl_fmt_dummy;
444  pxl_fmt_dummy.ff_id = AV_PIX_FMT_NONE;
445  for (int i = 0; avf_pixel_formats[i].ff_id != AV_PIX_FMT_NONE; i++) {
446  if ([pxl_fmt intValue] == avf_pixel_formats[i].avf_id) {
447  pxl_fmt_dummy = avf_pixel_formats[i];
448  break;
449  }
450  }
451 
452  if (pxl_fmt_dummy.ff_id != AV_PIX_FMT_NONE) {
453  av_log(s, AV_LOG_ERROR, " %s\n", av_get_pix_fmt_name(pxl_fmt_dummy.ff_id));
454 
455  // select first supported pixel format instead of user selected (or default) pixel format
456  if (pxl_fmt_spec.ff_id == AV_PIX_FMT_NONE) {
457  pxl_fmt_spec = pxl_fmt_dummy;
458  }
459  }
460  }
461 
462  // fail if there is no appropriate pixel format or print a warning about overriding the pixel format
463  if (pxl_fmt_spec.ff_id == AV_PIX_FMT_NONE) {
464  return 1;
465  } else {
466  av_log(s, AV_LOG_WARNING, "Overriding selected pixel format to use %s instead.\n",
467  av_get_pix_fmt_name(pxl_fmt_spec.ff_id));
468  }
469  }
470 
471  ctx->pixel_format = pxl_fmt_spec.ff_id;
472  pixel_format = [NSNumber numberWithUnsignedInt:pxl_fmt_spec.avf_id];
473  capture_dict = [NSDictionary dictionaryWithObject:pixel_format
474  forKey:(id)kCVPixelBufferPixelFormatTypeKey];
475 
476  [ctx->video_output setVideoSettings:capture_dict];
477  [ctx->video_output setAlwaysDiscardsLateVideoFrames:YES];
478 
479  ctx->avf_delegate = [[AVFFrameReceiver alloc] initWithContext:ctx];
480 
481  queue = dispatch_queue_create("avf_queue", NULL);
482  [ctx->video_output setSampleBufferDelegate:ctx->avf_delegate queue:queue];
483  dispatch_release(queue);
484 
485  if ([ctx->capture_session canAddOutput:ctx->video_output]) {
486  [ctx->capture_session addOutput:ctx->video_output];
487  } else {
488  av_log(s, AV_LOG_ERROR, "can't add video output to capture session\n");
489  return 1;
490  }
491 
492  return 0;
493 }
494 
495 static int add_audio_device(AVFormatContext *s, AVCaptureDevice *audio_device)
496 {
498  NSError *error = nil;
499  AVCaptureDeviceInput* audio_dev_input = [[[AVCaptureDeviceInput alloc] initWithDevice:audio_device error:&error] autorelease];
500  dispatch_queue_t queue;
501 
502  if (!audio_dev_input) {
503  av_log(s, AV_LOG_ERROR, "Failed to create AV capture input device: %s\n",
504  [[error localizedDescription] UTF8String]);
505  return 1;
506  }
507 
508  if ([ctx->capture_session canAddInput:audio_dev_input]) {
509  [ctx->capture_session addInput:audio_dev_input];
510  } else {
511  av_log(s, AV_LOG_ERROR, "can't add audio input to capture session\n");
512  return 1;
513  }
514 
515  // Attaching output
516  ctx->audio_output = [[AVCaptureAudioDataOutput alloc] init];
517 
518  if (!ctx->audio_output) {
519  av_log(s, AV_LOG_ERROR, "Failed to init AV audio output\n");
520  return 1;
521  }
522 
523  ctx->avf_audio_delegate = [[AVFAudioReceiver alloc] initWithContext:ctx];
524 
525  queue = dispatch_queue_create("avf_audio_queue", NULL);
526  [ctx->audio_output setSampleBufferDelegate:ctx->avf_audio_delegate queue:queue];
527  dispatch_release(queue);
528 
529  if ([ctx->capture_session canAddOutput:ctx->audio_output]) {
530  [ctx->capture_session addOutput:ctx->audio_output];
531  } else {
532  av_log(s, AV_LOG_ERROR, "adding audio output to capture session failed\n");
533  return 1;
534  }
535 
536  return 0;
537 }
538 
540 {
542  CVImageBufferRef image_buffer;
543  CGSize image_buffer_size;
544  AVStream* stream = avformat_new_stream(s, NULL);
545 
546  if (!stream) {
547  return 1;
548  }
549 
550  // Take stream info from the first frame.
551  while (ctx->frames_captured < 1) {
552  CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, YES);
553  }
554 
555  lock_frames(ctx);
556 
557  ctx->video_stream_index = stream->index;
558 
559  avpriv_set_pts_info(stream, 64, 1, avf_time_base);
560 
561  image_buffer = CMSampleBufferGetImageBuffer(ctx->current_frame);
562  image_buffer_size = CVImageBufferGetEncodedSize(image_buffer);
563 
564  stream->codecpar->codec_id = AV_CODEC_ID_RAWVIDEO;
565  stream->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
566  stream->codecpar->width = (int)image_buffer_size.width;
567  stream->codecpar->height = (int)image_buffer_size.height;
568  stream->codecpar->format = ctx->pixel_format;
569 
570  CFRelease(ctx->current_frame);
571  ctx->current_frame = nil;
572 
573  unlock_frames(ctx);
574 
575  return 0;
576 }
577 
579 {
581  CMFormatDescriptionRef format_desc;
582  AVStream* stream = avformat_new_stream(s, NULL);
583 
584  if (!stream) {
585  return 1;
586  }
587 
588  // Take stream info from the first frame.
589  while (ctx->audio_frames_captured < 1) {
590  CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, YES);
591  }
592 
593  lock_frames(ctx);
594 
595  ctx->audio_stream_index = stream->index;
596 
597  avpriv_set_pts_info(stream, 64, 1, avf_time_base);
598 
599  format_desc = CMSampleBufferGetFormatDescription(ctx->current_audio_frame);
600  const AudioStreamBasicDescription *basic_desc = CMAudioFormatDescriptionGetStreamBasicDescription(format_desc);
601 
602  if (!basic_desc) {
603  av_log(s, AV_LOG_ERROR, "audio format not available\n");
604  return 1;
605  }
606 
607  stream->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
608  stream->codecpar->sample_rate = basic_desc->mSampleRate;
609  stream->codecpar->channels = basic_desc->mChannelsPerFrame;
610  stream->codecpar->channel_layout = av_get_default_channel_layout(stream->codecpar->channels);
611 
612  ctx->audio_channels = basic_desc->mChannelsPerFrame;
613  ctx->audio_bits_per_sample = basic_desc->mBitsPerChannel;
614  ctx->audio_float = basic_desc->mFormatFlags & kAudioFormatFlagIsFloat;
615  ctx->audio_be = basic_desc->mFormatFlags & kAudioFormatFlagIsBigEndian;
616  ctx->audio_signed_integer = basic_desc->mFormatFlags & kAudioFormatFlagIsSignedInteger;
617  ctx->audio_packed = basic_desc->mFormatFlags & kAudioFormatFlagIsPacked;
618  ctx->audio_non_interleaved = basic_desc->mFormatFlags & kAudioFormatFlagIsNonInterleaved;
619 
620  if (basic_desc->mFormatID == kAudioFormatLinearPCM &&
621  ctx->audio_float &&
622  ctx->audio_bits_per_sample == 32 &&
623  ctx->audio_packed) {
624  stream->codecpar->codec_id = ctx->audio_be ? AV_CODEC_ID_PCM_F32BE : AV_CODEC_ID_PCM_F32LE;
625  } else if (basic_desc->mFormatID == kAudioFormatLinearPCM &&
626  ctx->audio_signed_integer &&
627  ctx->audio_bits_per_sample == 16 &&
628  ctx->audio_packed) {
629  stream->codecpar->codec_id = ctx->audio_be ? AV_CODEC_ID_PCM_S16BE : AV_CODEC_ID_PCM_S16LE;
630  } else if (basic_desc->mFormatID == kAudioFormatLinearPCM &&
631  ctx->audio_signed_integer &&
632  ctx->audio_bits_per_sample == 24 &&
633  ctx->audio_packed) {
634  stream->codecpar->codec_id = ctx->audio_be ? AV_CODEC_ID_PCM_S24BE : AV_CODEC_ID_PCM_S24LE;
635  } else if (basic_desc->mFormatID == kAudioFormatLinearPCM &&
636  ctx->audio_signed_integer &&
637  ctx->audio_bits_per_sample == 32 &&
638  ctx->audio_packed) {
639  stream->codecpar->codec_id = ctx->audio_be ? AV_CODEC_ID_PCM_S32BE : AV_CODEC_ID_PCM_S32LE;
640  } else {
641  av_log(s, AV_LOG_ERROR, "audio format is not supported\n");
642  return 1;
643  }
644 
645  if (ctx->audio_non_interleaved) {
646  CMBlockBufferRef block_buffer = CMSampleBufferGetDataBuffer(ctx->current_audio_frame);
647  ctx->audio_buffer_size = CMBlockBufferGetDataLength(block_buffer);
649  if (!ctx->audio_buffer) {
650  av_log(s, AV_LOG_ERROR, "error allocating audio buffer\n");
651  return 1;
652  }
653  }
654 
655  CFRelease(ctx->current_audio_frame);
656  ctx->current_audio_frame = nil;
657 
658  unlock_frames(ctx);
659 
660  return 0;
661 }
662 
664 {
665  NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
666  int capture_screen = 0;
667  uint32_t num_screens = 0;
669  AVCaptureDevice *video_device = nil;
670  AVCaptureDevice *audio_device = nil;
671  // Find capture device
672  NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
673  ctx->num_video_devices = [devices count];
674 
675  ctx->first_pts = av_gettime();
676  ctx->first_audio_pts = av_gettime();
677 
680 
681 #if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
682  CGGetActiveDisplayList(0, NULL, &num_screens);
683 #endif
684 
685  // List devices if requested
686  if (ctx->list_devices) {
687  int index = 0;
688  av_log(ctx, AV_LOG_INFO, "AVFoundation video devices:\n");
689  for (AVCaptureDevice *device in devices) {
690  const char *name = [[device localizedName] UTF8String];
691  index = [devices indexOfObject:device];
692  av_log(ctx, AV_LOG_INFO, "[%d] %s\n", index, name);
693  index++;
694  }
695 #if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
696  if (num_screens > 0) {
697  CGDirectDisplayID screens[num_screens];
698  CGGetActiveDisplayList(num_screens, screens, &num_screens);
699  for (int i = 0; i < num_screens; i++) {
700  av_log(ctx, AV_LOG_INFO, "[%d] Capture screen %d\n", index + i, i);
701  }
702  }
703 #endif
704 
705  av_log(ctx, AV_LOG_INFO, "AVFoundation audio devices:\n");
706  devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeAudio];
707  for (AVCaptureDevice *device in devices) {
708  const char *name = [[device localizedName] UTF8String];
709  int index = [devices indexOfObject:device];
710  av_log(ctx, AV_LOG_INFO, "[%d] %s\n", index, name);
711  }
712  goto fail;
713  }
714 
715  // parse input filename for video and audio device
717 
718  // check for device index given in filename
719  if (ctx->video_device_index == -1 && ctx->video_filename) {
720  sscanf(ctx->video_filename, "%d", &ctx->video_device_index);
721  }
722  if (ctx->audio_device_index == -1 && ctx->audio_filename) {
723  sscanf(ctx->audio_filename, "%d", &ctx->audio_device_index);
724  }
725 
726  if (ctx->video_device_index >= 0) {
727  if (ctx->video_device_index < ctx->num_video_devices) {
728  video_device = [devices objectAtIndex:ctx->video_device_index];
729  } else if (ctx->video_device_index < ctx->num_video_devices + num_screens) {
730 #if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
731  CGDirectDisplayID screens[num_screens];
732  CGGetActiveDisplayList(num_screens, screens, &num_screens);
733  AVCaptureScreenInput* capture_screen_input = [[[AVCaptureScreenInput alloc] initWithDisplayID:screens[ctx->video_device_index - ctx->num_video_devices]] autorelease];
734 
735  if (ctx->framerate.num > 0) {
736  capture_screen_input.minFrameDuration = CMTimeMake(ctx->framerate.den, ctx->framerate.num);
737  }
738 
739 #if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1080
740  if (ctx->capture_cursor) {
741  capture_screen_input.capturesCursor = YES;
742  } else {
743  capture_screen_input.capturesCursor = NO;
744  }
745 #endif
746 
747  if (ctx->capture_mouse_clicks) {
748  capture_screen_input.capturesMouseClicks = YES;
749  } else {
750  capture_screen_input.capturesMouseClicks = NO;
751  }
752 
753  video_device = (AVCaptureDevice*) capture_screen_input;
754  capture_screen = 1;
755 #endif
756  } else {
757  av_log(ctx, AV_LOG_ERROR, "Invalid device index\n");
758  goto fail;
759  }
760  } else if (ctx->video_filename &&
761  strncmp(ctx->video_filename, "none", 4)) {
762  if (!strncmp(ctx->video_filename, "default", 7)) {
763  video_device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
764  } else {
765  // looking for video inputs
766  for (AVCaptureDevice *device in devices) {
767  if (!strncmp(ctx->video_filename, [[device localizedName] UTF8String], strlen(ctx->video_filename))) {
768  video_device = device;
769  break;
770  }
771  }
772 
773 #if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
774  // looking for screen inputs
775  if (!video_device) {
776  int idx;
777  if(sscanf(ctx->video_filename, "Capture screen %d", &idx) && idx < num_screens) {
778  CGDirectDisplayID screens[num_screens];
779  CGGetActiveDisplayList(num_screens, screens, &num_screens);
780  AVCaptureScreenInput* capture_screen_input = [[[AVCaptureScreenInput alloc] initWithDisplayID:screens[idx]] autorelease];
781  video_device = (AVCaptureDevice*) capture_screen_input;
782  ctx->video_device_index = ctx->num_video_devices + idx;
783  capture_screen = 1;
784 
785  if (ctx->framerate.num > 0) {
786  capture_screen_input.minFrameDuration = CMTimeMake(ctx->framerate.den, ctx->framerate.num);
787  }
788 
789 #if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1080
790  if (ctx->capture_cursor) {
791  capture_screen_input.capturesCursor = YES;
792  } else {
793  capture_screen_input.capturesCursor = NO;
794  }
795 #endif
796 
797  if (ctx->capture_mouse_clicks) {
798  capture_screen_input.capturesMouseClicks = YES;
799  } else {
800  capture_screen_input.capturesMouseClicks = NO;
801  }
802  }
803  }
804 #endif
805  }
806 
807  if (!video_device) {
808  av_log(ctx, AV_LOG_ERROR, "Video device not found\n");
809  goto fail;
810  }
811  }
812 
813  // get audio device
814  if (ctx->audio_device_index >= 0) {
815  NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeAudio];
816 
817  if (ctx->audio_device_index >= [devices count]) {
818  av_log(ctx, AV_LOG_ERROR, "Invalid audio device index\n");
819  goto fail;
820  }
821 
822  audio_device = [devices objectAtIndex:ctx->audio_device_index];
823  } else if (ctx->audio_filename &&
824  strncmp(ctx->audio_filename, "none", 4)) {
825  if (!strncmp(ctx->audio_filename, "default", 7)) {
826  audio_device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeAudio];
827  } else {
828  NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeAudio];
829 
830  for (AVCaptureDevice *device in devices) {
831  if (!strncmp(ctx->audio_filename, [[device localizedName] UTF8String], strlen(ctx->audio_filename))) {
832  audio_device = device;
833  break;
834  }
835  }
836  }
837 
838  if (!audio_device) {
839  av_log(ctx, AV_LOG_ERROR, "Audio device not found\n");
840  goto fail;
841  }
842  }
843 
844  // Video nor Audio capture device not found, looking for AVMediaTypeVideo/Audio
845  if (!video_device && !audio_device) {
846  av_log(s, AV_LOG_ERROR, "No AV capture device found\n");
847  goto fail;
848  }
849 
850  if (video_device) {
851  if (ctx->video_device_index < ctx->num_video_devices) {
852  av_log(s, AV_LOG_DEBUG, "'%s' opened\n", [[video_device localizedName] UTF8String]);
853  } else {
854  av_log(s, AV_LOG_DEBUG, "'%s' opened\n", [[video_device description] UTF8String]);
855  }
856  }
857  if (audio_device) {
858  av_log(s, AV_LOG_DEBUG, "audio device '%s' opened\n", [[audio_device localizedName] UTF8String]);
859  }
860 
861  // Initialize capture session
862  ctx->capture_session = [[AVCaptureSession alloc] init];
863 
864  if (video_device && add_video_device(s, video_device)) {
865  goto fail;
866  }
867  if (audio_device && add_audio_device(s, audio_device)) {
868  }
869 
870  [ctx->capture_session startRunning];
871 
872  /* Unlock device configuration only after the session is started so it
873  * does not reset the capture formats */
874  if (!capture_screen) {
875  [video_device unlockForConfiguration];
876  }
877 
878  if (video_device && get_video_config(s)) {
879  goto fail;
880  }
881 
882  // set audio stream
883  if (audio_device && get_audio_config(s)) {
884  goto fail;
885  }
886 
887  [pool release];
888  return 0;
889 
890 fail:
891  [pool release];
892  destroy_context(ctx);
893  return AVERROR(EIO);
894 }
895 
897  CVPixelBufferRef image_buffer,
898  AVPacket *pkt)
899 {
900  AVFContext *ctx = s->priv_data;
901  int src_linesize[4];
902  const uint8_t *src_data[4];
903  int width = CVPixelBufferGetWidth(image_buffer);
904  int height = CVPixelBufferGetHeight(image_buffer);
905  int status;
906 
907  memset(src_linesize, 0, sizeof(src_linesize));
908  memset(src_data, 0, sizeof(src_data));
909 
910  status = CVPixelBufferLockBaseAddress(image_buffer, 0);
911  if (status != kCVReturnSuccess) {
912  av_log(s, AV_LOG_ERROR, "Could not lock base address: %d\n", status);
913  return AVERROR_EXTERNAL;
914  }
915 
916  if (CVPixelBufferIsPlanar(image_buffer)) {
917  size_t plane_count = CVPixelBufferGetPlaneCount(image_buffer);
918  int i;
919  for(i = 0; i < plane_count; i++){
920  src_linesize[i] = CVPixelBufferGetBytesPerRowOfPlane(image_buffer, i);
921  src_data[i] = CVPixelBufferGetBaseAddressOfPlane(image_buffer, i);
922  }
923  } else {
924  src_linesize[0] = CVPixelBufferGetBytesPerRow(image_buffer);
925  src_data[0] = CVPixelBufferGetBaseAddress(image_buffer);
926  }
927 
928  status = av_image_copy_to_buffer(pkt->data, pkt->size,
929  src_data, src_linesize,
930  ctx->pixel_format, width, height, 1);
931 
932 
933 
934  CVPixelBufferUnlockBaseAddress(image_buffer, 0);
935 
936  return status;
937 }
938 
940 {
942 
943  do {
944  CVImageBufferRef image_buffer;
945  lock_frames(ctx);
946 
947  image_buffer = CMSampleBufferGetImageBuffer(ctx->current_frame);
948 
949  if (ctx->current_frame != nil) {
950  int status;
951  if (av_new_packet(pkt, (int)CVPixelBufferGetDataSize(image_buffer)) < 0) {
952  return AVERROR(EIO);
953  }
954 
955  CMItemCount count;
956  CMSampleTimingInfo timing_info;
957 
958  if (CMSampleBufferGetOutputSampleTimingInfoArray(ctx->current_frame, 1, &timing_info, &count) == noErr) {
959  AVRational timebase_q = av_make_q(1, timing_info.presentationTimeStamp.timescale);
960  pkt->pts = pkt->dts = av_rescale_q(timing_info.presentationTimeStamp.value, timebase_q, avf_time_base_q);
961  }
962 
963  pkt->stream_index = ctx->video_stream_index;
964  pkt->flags |= AV_PKT_FLAG_KEY;
965 
966  status = copy_cvpixelbuffer(s, image_buffer, pkt);
967  CFRelease(ctx->current_frame);
968  ctx->current_frame = nil;
969 
970  if (status < 0)
971  return status;
972  } else if (ctx->current_audio_frame != nil) {
973  CMBlockBufferRef block_buffer = CMSampleBufferGetDataBuffer(ctx->current_audio_frame);
974  int block_buffer_size = CMBlockBufferGetDataLength(block_buffer);
975 
976  if (!block_buffer || !block_buffer_size) {
977  return AVERROR(EIO);
978  }
979 
980  if (ctx->audio_non_interleaved && block_buffer_size > ctx->audio_buffer_size) {
982  }
983 
984  if (av_new_packet(pkt, block_buffer_size) < 0) {
985  return AVERROR(EIO);
986  }
987 
988  CMItemCount count;
989  CMSampleTimingInfo timing_info;
990 
991  if (CMSampleBufferGetOutputSampleTimingInfoArray(ctx->current_audio_frame, 1, &timing_info, &count) == noErr) {
992  AVRational timebase_q = av_make_q(1, timing_info.presentationTimeStamp.timescale);
993  pkt->pts = pkt->dts = av_rescale_q(timing_info.presentationTimeStamp.value, timebase_q, avf_time_base_q);
994  }
995 
996  pkt->stream_index = ctx->audio_stream_index;
997  pkt->flags |= AV_PKT_FLAG_KEY;
998 
999  if (ctx->audio_non_interleaved) {
1000  int sample, c, shift, num_samples;
1001 
1002  OSStatus ret = CMBlockBufferCopyDataBytes(block_buffer, 0, pkt->size, ctx->audio_buffer);
1003  if (ret != kCMBlockBufferNoErr) {
1004  return AVERROR(EIO);
1005  }
1006 
1007  num_samples = pkt->size / (ctx->audio_channels * (ctx->audio_bits_per_sample >> 3));
1008 
1009  // transform decoded frame into output format
1010  #define INTERLEAVE_OUTPUT(bps) \
1011  { \
1012  int##bps##_t **src; \
1013  int##bps##_t *dest; \
1014  src = av_malloc(ctx->audio_channels * sizeof(int##bps##_t*)); \
1015  if (!src) return AVERROR(EIO); \
1016  for (c = 0; c < ctx->audio_channels; c++) { \
1017  src[c] = ((int##bps##_t*)ctx->audio_buffer) + c * num_samples; \
1018  } \
1019  dest = (int##bps##_t*)pkt->data; \
1020  shift = bps - ctx->audio_bits_per_sample; \
1021  for (sample = 0; sample < num_samples; sample++) \
1022  for (c = 0; c < ctx->audio_channels; c++) \
1023  *dest++ = src[c][sample] << shift; \
1024  av_freep(&src); \
1025  }
1026 
1027  if (ctx->audio_bits_per_sample <= 16) {
1028  INTERLEAVE_OUTPUT(16)
1029  } else {
1030  INTERLEAVE_OUTPUT(32)
1031  }
1032  } else {
1033  OSStatus ret = CMBlockBufferCopyDataBytes(block_buffer, 0, pkt->size, pkt->data);
1034  if (ret != kCMBlockBufferNoErr) {
1035  return AVERROR(EIO);
1036  }
1037  }
1038 
1039  CFRelease(ctx->current_audio_frame);
1040  ctx->current_audio_frame = nil;
1041  } else {
1042  pkt->data = NULL;
1044  }
1045 
1046  unlock_frames(ctx);
1047  } while (!pkt->data);
1048 
1049  return 0;
1050 }
1051 
1053 {
1055  destroy_context(ctx);
1056  return 0;
1057 }
1058 
1059 static const AVOption options[] = {
1060  { "list_devices", "list available devices", offsetof(AVFContext, list_devices), AV_OPT_TYPE_INT, {.i64=0}, 0, 1, AV_OPT_FLAG_DECODING_PARAM, "list_devices" },
1061  { "true", "", 0, AV_OPT_TYPE_CONST, {.i64=1}, 0, 0, AV_OPT_FLAG_DECODING_PARAM, "list_devices" },
1062  { "false", "", 0, AV_OPT_TYPE_CONST, {.i64=0}, 0, 0, AV_OPT_FLAG_DECODING_PARAM, "list_devices" },
1063  { "video_device_index", "select video device by index for devices with same name (starts at 0)", offsetof(AVFContext, video_device_index), AV_OPT_TYPE_INT, {.i64 = -1}, -1, INT_MAX, AV_OPT_FLAG_DECODING_PARAM },
1064  { "audio_device_index", "select audio device by index for devices with same name (starts at 0)", offsetof(AVFContext, audio_device_index), AV_OPT_TYPE_INT, {.i64 = -1}, -1, INT_MAX, AV_OPT_FLAG_DECODING_PARAM },
1065  { "pixel_format", "set pixel format", offsetof(AVFContext, pixel_format), AV_OPT_TYPE_PIXEL_FMT, {.i64 = AV_PIX_FMT_YUV420P}, 0, INT_MAX, AV_OPT_FLAG_DECODING_PARAM},
1066  { "framerate", "set frame rate", offsetof(AVFContext, framerate), AV_OPT_TYPE_VIDEO_RATE, {.str = "ntsc"}, 0, INT_MAX, AV_OPT_FLAG_DECODING_PARAM },
1067  { "video_size", "set video size", offsetof(AVFContext, width), AV_OPT_TYPE_IMAGE_SIZE, {.str = NULL}, 0, 0, AV_OPT_FLAG_DECODING_PARAM },
1068  { "capture_cursor", "capture the screen cursor", offsetof(AVFContext, capture_cursor), AV_OPT_TYPE_INT, {.i64=0}, 0, 1, AV_OPT_FLAG_DECODING_PARAM },
1069  { "capture_mouse_clicks", "capture the screen mouse clicks", offsetof(AVFContext, capture_mouse_clicks), AV_OPT_TYPE_INT, {.i64=0}, 0, 1, AV_OPT_FLAG_DECODING_PARAM },
1070 
1071  { NULL },
1072 };
1073 
1074 static const AVClass avf_class = {
1075  .class_name = "AVFoundation input device",
1076  .item_name = av_default_item_name,
1077  .option = options,
1078  .version = LIBAVUTIL_VERSION_INT,
1080 };
1081 
1083  .name = "avfoundation",
1084  .long_name = NULL_IF_CONFIG_SMALL("AVFoundation input device"),
1085  .priv_data_size = sizeof(AVFContext),
1088  .read_close = avf_close,
1089  .flags = AVFMT_NOFILE,
1090  .priv_class = &avf_class,
1091 };
packed YUV 4:2:2, 16bpp, Cb Y0 Cr Y1
Definition: pixfmt.h:81
int audio_buffer_size
Definition: avfoundation.m:121
#define NULL
Definition: coverity.c:32
static const struct AVFPixelFormatSpec avf_pixel_formats[]
Definition: avfoundation.m:53
static void lock_frames(AVFContext *ctx)
Definition: avfoundation.m:132
static int shift(int a, int b)
Definition: sonic.c:82
static av_always_inline int pthread_mutex_destroy(pthread_mutex_t *mutex)
Definition: os2threads.h:108
static const char * format[]
Definition: af_aiir.c:330
#define pthread_mutex_lock(a)
Definition: ffprobe.c:61
AVCaptureSession * capture_session
Definition: avfoundation.m:125
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
int32_t * audio_buffer
Definition: avfoundation.m:120
int av_image_copy_to_buffer(uint8_t *dst, int dst_size, const uint8_t *const src_data[4], const int src_linesize[4], enum AVPixelFormat pix_fmt, int width, int height, int align)
Copy image data from an image into a buffer.
Definition: imgutils.c:453
planar YUV 4:4:4, 24bpp, (1 Cr & Cb sample per 1x1 Y samples)
Definition: pixfmt.h:71
misc image utilities
#define AV_LOG_WARNING
Something somehow does not look correct.
Definition: log.h:182
#define LIBAVUTIL_VERSION_INT
Definition: version.h:85
packed RGB 8:8:8, 24bpp, RGBRGB...
Definition: pixfmt.h:68
int list_devices
Definition: avfoundation.m:101
void avpriv_set_pts_info(AVStream *s, int pts_wrap_bits, unsigned int pts_num, unsigned int pts_den)
Set the time base and wrapping info for a given stream.
Definition: utils.c:4881
static av_cold int init(AVCodecContext *avctx)
Definition: avrndec.c:35
int audio_frames_captured
Definition: avfoundation.m:87
AVFContext * _context
Definition: avfoundation.m:192
static const AVOption options[]
int num
Numerator.
Definition: rational.h:59
packed RGB 5:5:5, 16bpp, (msb)1X 5R 5G 5B(lsb), little-endian, X=unused/undefined ...
Definition: pixfmt.h:108
int size
Definition: avcodec.h:1445
static int add_video_device(AVFormatContext *s, AVCaptureDevice *video_device)
Definition: avfoundation.m:367
const char * av_default_item_name(void *ptr)
Return the context name.
Definition: log.c:191
CMSampleBufferRef current_audio_frame
Definition: avfoundation.m:129
static int get_audio_config(AVFormatContext *s)
Definition: avfoundation.m:578
int audio_non_interleaved
Definition: avfoundation.m:118
packed BGR 8:8:8, 32bpp, XBGRXBGR... X=unused/undefined
Definition: pixfmt.h:239
static AVPacket pkt
#define sample
AudioReciever class - delegate for AVCaptureSession.
Definition: avfoundation.m:190
static av_always_inline int pthread_cond_destroy(pthread_cond_t *cond)
Definition: os2threads.h:140
AVRational framerate
Definition: avfoundation.m:95
packed RGB 5:6:5, 16bpp, (msb) 5R 6G 5B(lsb), little-endian
Definition: pixfmt.h:106
int capture_mouse_clicks
Definition: avfoundation.m:99
Format I/O context.
Definition: avformat.h:1351
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
int audio_signed_integer
Definition: avfoundation.m:116
uint8_t
#define av_malloc(s)
packed RGB 8:8:8, 32bpp, RGBXRGBX... X=unused/undefined
Definition: pixfmt.h:238
AVOptions.
static int configure_video_device(AVFormatContext *s, AVCaptureDevice *video_device)
Configure the video device.
Definition: avfoundation.m:284
AVStream * avformat_new_stream(AVFormatContext *s, const AVCodec *c)
Add a new stream to a media file.
Definition: utils.c:4454
packed RGB 5:6:5, 16bpp, (msb) 5R 6G 5B(lsb), big-endian
Definition: pixfmt.h:105
#define height
uint8_t * data
Definition: avcodec.h:1444
static double av_q2d(AVRational a)
Convert an AVRational to a double.
Definition: rational.h:104
static av_cold int read_close(AVFormatContext *ctx)
Definition: libcdio.c:145
static av_always_inline int pthread_cond_signal(pthread_cond_t *cond)
Definition: os2threads.h:148
static int copy_cvpixelbuffer(AVFormatContext *s, CVPixelBufferRef image_buffer, AVPacket *pkt)
Definition: avfoundation.m:896
static void parse_device_name(AVFormatContext *s)
Definition: avfoundation.m:260
#define av_log(a,...)
#define AV_PKT_FLAG_KEY
The packet contains a keyframe.
Definition: avcodec.h:1476
AVInputFormat ff_avfoundation_demuxer
int64_t av_rescale_q(int64_t a, AVRational bq, AVRational cq)
Rescale a 64-bit integer by 2 rational numbers.
Definition: mathematics.c:142
Main libavdevice API header.
int av_new_packet(AVPacket *pkt, int size)
Allocate the payload of a packet and initialize its fields with default values.
Definition: avpacket.c:86
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition: log.h:176
char * video_filename
Definition: avfoundation.m:107
#define AVERROR(e)
Definition: error.h:43
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification. ...
Definition: internal.h:186
char * url
input or output URL.
Definition: avformat.h:1447
enum AVPixelFormat ff_id
Definition: avfoundation.m:49
#define AV_LOG_DEBUG
Stuff which is only useful for libav* developers.
Definition: log.h:197
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
static int avf_read_header(AVFormatContext *s)
Definition: avfoundation.m:663
#define AV_PIX_FMT_YUV444P10
Definition: pixfmt.h:382
int num_video_devices
Definition: avfoundation.m:110
GLsizei count
Definition: opengl_enc.c:109
int capture_cursor
Definition: avfoundation.m:98
#define fail()
Definition: checkasm.h:117
int flags
A combination of AV_PKT_FLAG values.
Definition: avcodec.h:1450
common internal API header
#define AVERROR_BUFFER_TOO_SMALL
Buffer too small.
Definition: error.h:51
#define width
typedef void(APIENTRY *FF_PFNGLACTIVETEXTUREPROC)(GLenum texture)
static const int avf_time_base
Definition: avfoundation.m:41
static int capture_screen(CCaptionSubContext *ctx)
Definition: ccaption_dec.c:435
int32_t
AVFormatContext * ctx
Definition: movenc.c:48
static av_always_inline int pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutexattr_t *attr)
Definition: os2threads.h:100
int frames_captured
Definition: avfoundation.m:86
#define s(width, name)
Definition: cbs_vp9.c:257
packed RGB 8:8:8, 24bpp, BGRBGR...
Definition: pixfmt.h:69
int audio_bits_per_sample
Definition: avfoundation.m:113
#define pthread_mutex_unlock(a)
Definition: ffprobe.c:65
packed RGB 16:16:16, 48bpp, 16B, 16G, 16R, the 2-byte value for each R/G/B component is stored as big...
Definition: pixfmt.h:148
static void error(const char *err)
static int read_header(FFV1Context *f)
Definition: ffv1dec.c:530
int64_t av_gettime(void)
Get the current time in microseconds.
Definition: time.c:39
Stream structure.
Definition: avformat.h:874
static int read_packet(void *opaque, uint8_t *buf, int buf_size)
Definition: avio_reading.c:42
static int add_audio_device(AVFormatContext *s, AVCaptureDevice *audio_device)
Definition: avfoundation.m:495
#define AV_LOG_INFO
Standard information.
Definition: log.h:187
char * av_strdup(const char *s)
Duplicate a string.
Definition: mem.c:251
int video_stream_index
Definition: avfoundation.m:103
planar YUV 4:4:4 32bpp, (1 Cr & Cb sample per 1x1 Y & A samples)
Definition: pixfmt.h:177
static AVRational av_make_q(int num, int den)
Create an AVRational.
Definition: rational.h:71
static const AVRational avf_time_base_q
Definition: avfoundation.m:43
packed YUV 4:2:2, 16bpp, Y0 Cb Y1 Cr
Definition: pixfmt.h:67
AVCaptureVideoDataOutput * video_output
Definition: avfoundation.m:126
uint8_t pi<< 24) CONV_FUNC_GROUP(AV_SAMPLE_FMT_FLT, float, AV_SAMPLE_FMT_U8, uint8_t,(*(constuint8_t *) pi-0x80)*(1.0f/(1<< 7))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_DBL, double, AV_SAMPLE_FMT_U8, uint8_t,(*(constuint8_t *) pi-0x80)*(1.0/(1<< 7))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_U8, uint8_t, AV_SAMPLE_FMT_S16, int16_t,(*(constint16_t *) pi >>8)+0x80) CONV_FUNC_GROUP(AV_SAMPLE_FMT_FLT, float, AV_SAMPLE_FMT_S16, int16_t,*(constint16_t *) pi *(1.0f/(1<< 15))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_DBL, double, AV_SAMPLE_FMT_S16, int16_t,*(constint16_t *) pi *(1.0/(1<< 15))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_U8, uint8_t, AV_SAMPLE_FMT_S32, int32_t,(*(constint32_t *) pi >>24)+0x80) CONV_FUNC_GROUP(AV_SAMPLE_FMT_FLT, float, AV_SAMPLE_FMT_S32, int32_t,*(constint32_t *) pi *(1.0f/(1U<< 31))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_DBL, double, AV_SAMPLE_FMT_S32, int32_t,*(constint32_t *) pi *(1.0/(1U<< 31))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_U8, uint8_t, AV_SAMPLE_FMT_FLT, float, av_clip_uint8(lrintf(*(constfloat *) pi *(1<< 7))+0x80)) CONV_FUNC_GROUP(AV_SAMPLE_FMT_S16, int16_t, AV_SAMPLE_FMT_FLT, float, av_clip_int16(lrintf(*(constfloat *) pi *(1<< 15)))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_S32, int32_t, AV_SAMPLE_FMT_FLT, float, av_clipl_int32(llrintf(*(constfloat *) pi *(1U<< 31)))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_U8, uint8_t, AV_SAMPLE_FMT_DBL, double, av_clip_uint8(lrint(*(constdouble *) pi *(1<< 7))+0x80)) CONV_FUNC_GROUP(AV_SAMPLE_FMT_S16, int16_t, AV_SAMPLE_FMT_DBL, double, av_clip_int16(lrint(*(constdouble *) pi *(1<< 15)))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_S32, int32_t, AV_SAMPLE_FMT_DBL, double, av_clipl_int32(llrint(*(constdouble *) pi *(1U<< 31))))#defineSET_CONV_FUNC_GROUP(ofmt, ifmt) staticvoidset_generic_function(AudioConvert *ac){}voidff_audio_convert_free(AudioConvert **ac){if(!*ac) return;ff_dither_free(&(*ac) ->dc);av_freep(ac);}AudioConvert *ff_audio_convert_alloc(AVAudioResampleContext *avr, enumAVSampleFormatout_fmt, enumAVSampleFormatin_fmt, intchannels, intsample_rate, intapply_map){AudioConvert *ac;intin_planar, out_planar;ac=av_mallocz(sizeof(*ac));if(!ac) returnNULL;ac->avr=avr;ac->out_fmt=out_fmt;ac->in_fmt=in_fmt;ac->channels=channels;ac->apply_map=apply_map;if(avr->dither_method!=AV_RESAMPLE_DITHER_NONE &&av_get_packed_sample_fmt(out_fmt)==AV_SAMPLE_FMT_S16 &&av_get_bytes_per_sample(in_fmt)>2){ac->dc=ff_dither_alloc(avr, out_fmt, in_fmt, channels, sample_rate, apply_map);if(!ac->dc){av_free(ac);returnNULL;}returnac;}in_planar=ff_sample_fmt_is_planar(in_fmt, channels);out_planar=ff_sample_fmt_is_planar(out_fmt, channels);if(in_planar==out_planar){ac->func_type=CONV_FUNC_TYPE_FLAT;ac->planes=in_planar?ac->channels:1;}elseif(in_planar) ac->func_type=CONV_FUNC_TYPE_INTERLEAVE;elseac->func_type=CONV_FUNC_TYPE_DEINTERLEAVE;set_generic_function(ac);if(ARCH_AARCH64) ff_audio_convert_init_aarch64(ac);if(ARCH_ARM) ff_audio_convert_init_arm(ac);if(ARCH_X86) ff_audio_convert_init_x86(ac);returnac;}intff_audio_convert(AudioConvert *ac, AudioData *out, AudioData *in){intuse_generic=1;intlen=in->nb_samples;intp;if(ac->dc){av_log(ac->avr, AV_LOG_TRACE,"%dsamples-audio_convert:%sto%s(dithered)\n", len, av_get_sample_fmt_name(ac->in_fmt), av_get_sample_fmt_name(ac->out_fmt));returnff_convert_dither(ac-> in
pthread_mutex_t frame_lock
Definition: avfoundation.m:90
int audio_device_index
Definition: avfoundation.m:104
static int get_video_config(AVFormatContext *s)
Definition: avfoundation.m:539
static const AVClass avf_class
Describe the class of an AVClass context structure.
Definition: log.h:67
planar YUV 4:4:4 64bpp, (1 Cr & Cb sample per 1x1 Y & A samples, little-endian)
Definition: pixfmt.h:195
int index
Definition: gxfenc.c:89
#define INTERLEAVE_OUTPUT(bps)
Rational number (pair of numerator and denominator).
Definition: rational.h:58
int audio_channels
Definition: avfoundation.m:112
#define AV_OPT_FLAG_DECODING_PARAM
a generic parameter which can be set by the user for demuxing or decoding
Definition: opt.h:277
static void unlock_frames(AVFContext *ctx)
Definition: avfoundation.m:137
offset must point to AVRational
Definition: opt.h:236
packed BGR 8:8:8, 32bpp, BGRXBGRX... X=unused/undefined
Definition: pixfmt.h:240
int64_t first_pts
Definition: avfoundation.m:88
FrameReciever class - delegate for AVCaptureSession.
Definition: avfoundation.m:144
offset must point to two consecutive integers
Definition: opt.h:233
int audio_packed
Definition: avfoundation.m:117
misc parsing utilities
CMSampleBufferRef current_frame
Definition: avfoundation.m:128
#define flags(name, subs,...)
Definition: cbs_av1.c:596
int audio_stream_index
Definition: avfoundation.m:105
#define AV_PIX_FMT_YUV422P10
Definition: pixfmt.h:380
packed RGB 5:5:5, 16bpp, (msb)1X 5R 5G 5B(lsb), big-endian , X=unused/undefined
Definition: pixfmt.h:107
enum AVPixelFormat pixel_format
Definition: avfoundation.m:123
char * av_strtok(char *s, const char *delim, char **saveptr)
Split the string into several tokens which can be accessed by successive calls to av_strtok()...
Definition: avstring.c:184
static int FUNC() timing_info(CodedBitstreamContext *ctx, RWContext *rw, AV1RawTimingInfo *current)
Y , 1bpp, 0 is black, 1 is white, in each byte pixels are ordered from the msb to the lsb...
Definition: pixfmt.h:76
int
char * audio_filename
Definition: avfoundation.m:108
planar YUV 4:2:0, 12bpp, (1 Cr & Cb sample per 2x2 Y samples)
Definition: pixfmt.h:66
Y , 8bpp.
Definition: pixfmt.h:74
_fmutex pthread_mutex_t
Definition: os2threads.h:49
if(ret< 0)
Definition: vf_mcdeint.c:279
AVCaptureAudioDataOutput * audio_output
Definition: avfoundation.m:127
#define AVFMT_NOFILE
Demuxer will use avio_open, no opened file should be provided by the caller.
Definition: avformat.h:465
static double c[64]
static void destroy_context(AVFContext *ctx)
Definition: avfoundation.m:234
static av_always_inline int pthread_cond_init(pthread_cond_t *cond, const pthread_condattr_t *attr)
Definition: os2threads.h:129
int den
Denominator.
Definition: rational.h:60
static int avf_read_packet(AVFormatContext *s, AVPacket *pkt)
Definition: avfoundation.m:939
AVFContext * _context
Definition: avfoundation.m:146
void * priv_data
Format private data.
Definition: avformat.h:1379
id avf_audio_delegate
Definition: avfoundation.m:93
static int avf_close(AVFormatContext *s)
int64_t first_audio_pts
Definition: avfoundation.m:89
pthread_cond_t frame_wait_cond
Definition: avfoundation.m:91
int64_t dts
Decompression timestamp in AVStream->time_base units; the time at which the packet is decompressed...
Definition: avcodec.h:1443
int64_t av_get_default_channel_layout(int nb_channels)
Return default channel layout for a given number of channels.
#define av_freep(p)
const char * name
A comma separated list of short names for the format.
Definition: avformat.h:647
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:2322
int stream_index
Definition: avcodec.h:1446
packed RGB 8:8:8, 32bpp, XRGBXRGB... X=unused/undefined
Definition: pixfmt.h:237
enum AVCodecID id
#define AVERROR_EXTERNAL
Generic error in an external library.
Definition: error.h:57
AVPixelFormat
Pixel format.
Definition: pixfmt.h:64
This structure stores compressed data.
Definition: avcodec.h:1421
#define AV_PIX_FMT_YUV422P16
Definition: pixfmt.h:391
int64_t pts
Presentation timestamp in AVStream->time_base units; the time at which the decompressed packet will b...
Definition: avcodec.h:1437
const char * name
Definition: opengl_enc.c:103
static uint8_t tmp[11]
Definition: aes_ctr.c:26
int video_device_index
Definition: avfoundation.m:102