28 #import <AVFoundation/AVFoundation.h>
77 #if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1080
135 #if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
136 AVCaptureDeviceTransportControlsPlaybackMode observed_mode;
160 - (void) captureOutput:(AVCaptureOutput *)captureOutput
161 didOutputSampleBuffer:(CMSampleBufferRef)videoFrame
162 fromConnection:(AVCaptureConnection *)connection;
170 if (
self = [super
init]) {
174 #if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
176 NSString *keyPath = NSStringFromSelector(
@selector(transportControlsPlaybackMode));
177 NSKeyValueObservingOptions
options = NSKeyValueObservingOptionNew;
179 [
_context->observed_device addObserver: self
191 #if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
193 NSString *keyPath = NSStringFromSelector(
@selector(transportControlsPlaybackMode));
194 [_context->observed_device removeObserver: self forKeyPath: keyPath];
200 - (void)observeValueForKeyPath:(NSString *)keyPath
202 change:(NSDictionary *)change
203 context:(
void *)context {
205 #if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
206 AVCaptureDeviceTransportControlsPlaybackMode
mode =
207 [change[NSKeyValueChangeNewKey] integerValue];
210 if (
mode == AVCaptureDeviceTransportControlsNotPlayingMode) {
217 [
super observeValueForKeyPath: keyPath
224 - (void) captureOutput:(AVCaptureOutput *)captureOutput
225 didOutputSampleBuffer:(CMSampleBufferRef)videoFrame
226 fromConnection:(AVCaptureConnection *)connection
252 - (void) captureOutput:(AVCaptureOutput *)captureOutput
253 didOutputSampleBuffer:(CMSampleBufferRef)audioFrame
254 fromConnection:(AVCaptureConnection *)connection;
262 if (
self = [super
init]) {
268 - (void) captureOutput:(AVCaptureOutput *)captureOutput
269 didOutputSampleBuffer:(CMSampleBufferRef)audioFrame
270 fromConnection:(AVCaptureConnection *)connection
289 [ctx->capture_session stopRunning];
291 [ctx->capture_session release];
292 [ctx->video_output release];
293 [ctx->audio_output release];
294 [ctx->avf_delegate release];
295 [ctx->avf_audio_delegate release];
301 ctx->avf_audio_delegate =
NULL;
308 if (
ctx->current_frame) {
309 CFRelease(
ctx->current_frame);
346 NSObject *
range = nil;
348 NSObject *selected_range = nil;
349 NSObject *selected_format = nil;
355 for (
format in [video_device valueForKey:
@"formats"]) {
356 CMFormatDescriptionRef formatDescription;
357 CMVideoDimensions dimensions;
359 formatDescription = (CMFormatDescriptionRef) [
format performSelector:
@selector(formatDescription)];
360 dimensions = CMVideoFormatDescriptionGetDimensions(formatDescription);
362 if ((
ctx->width == 0 &&
ctx->height == 0) ||
363 (dimensions.width ==
ctx->width && dimensions.height ==
ctx->height)) {
367 for (
range in [
format valueForKey:
@"videoSupportedFrameRateRanges"]) {
368 double max_framerate;
370 [[range valueForKey:@"maxFrameRate"] getValue:&max_framerate];
372 selected_range =
range;
379 if (!selected_format) {
382 goto unsupported_format;
385 if (!selected_range) {
388 if (
ctx->video_is_muxed) {
391 goto unsupported_format;
395 if ([video_device lockForConfiguration:
NULL] == YES) {
396 if (selected_format) {
397 [video_device setValue:selected_format forKey:@"activeFormat"];
399 if (selected_range) {
400 NSValue *min_frame_duration = [selected_range valueForKey:@"minFrameDuration"];
401 [video_device setValue:min_frame_duration forKey:@"activeVideoMinFrameDuration"];
402 [video_device setValue:min_frame_duration forKey:@"activeVideoMaxFrameDuration"];
408 }
@catch(NSException *e) {
417 for (
format in [video_device valueForKey:
@"formats"]) {
418 CMFormatDescriptionRef formatDescription;
419 CMVideoDimensions dimensions;
421 formatDescription = (CMFormatDescriptionRef) [
format performSelector:
@selector(formatDescription)];
422 dimensions = CMVideoFormatDescriptionGetDimensions(formatDescription);
424 for (
range in [
format valueForKey:
@"videoSupportedFrameRateRanges"]) {
425 double min_framerate;
426 double max_framerate;
428 [[range valueForKey:@"minFrameRate"] getValue:&min_framerate];
429 [[range valueForKey:@"maxFrameRate"] getValue:&max_framerate];
431 dimensions.width, dimensions.height,
432 min_framerate, max_framerate);
442 NSError *
error = nil;
443 AVCaptureInput* capture_input = nil;
445 NSNumber *pixel_format;
446 NSDictionary *capture_dict;
447 dispatch_queue_t queue;
449 if (
ctx->video_device_index <
ctx->num_video_devices) {
450 capture_input = (AVCaptureInput*) [[[AVCaptureDeviceInput alloc] initWithDevice:video_device
error:&
error] autorelease];
452 capture_input = (AVCaptureInput*) video_device;
455 if (!capture_input) {
457 [[
error localizedDescription] UTF8String]);
461 if ([
ctx->capture_session canAddInput:capture_input]) {
462 [ctx->capture_session addInput:capture_input];
469 ctx->video_output = [[AVCaptureVideoDataOutput alloc] init];
471 if (!
ctx->video_output) {
481 }
@catch (NSException *exception) {
482 if (![[exception
name] isEqualToString:NSUndefinedKeyException]) {
506 if ([[
ctx->video_output availableVideoCVPixelFormatTypes] indexOfObject:[NSNumber numberWithInt:pxl_fmt_spec.avf_id]] == NSNotFound) {
507 av_log(
s,
AV_LOG_ERROR,
"Selected pixel format (%s) is not supported by the input device.\n",
513 for (NSNumber *pxl_fmt in [
ctx->video_output availableVideoCVPixelFormatTypes]) {
528 pxl_fmt_spec = pxl_fmt_dummy;
543 if (
ctx->capture_raw_data) {
544 ctx->pixel_format = pxl_fmt_spec.ff_id;
545 ctx->video_output.videoSettings = @{ };
547 ctx->pixel_format = pxl_fmt_spec.ff_id;
548 pixel_format = [NSNumber numberWithUnsignedInt:pxl_fmt_spec.avf_id];
549 capture_dict = [NSDictionary dictionaryWithObject:pixel_format
550 forKey:(id)kCVPixelBufferPixelFormatTypeKey];
552 [ctx->video_output setVideoSettings:capture_dict];
554 [ctx->video_output setAlwaysDiscardsLateVideoFrames:ctx->drop_late_frames];
556 #if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
558 if (!
ctx->video_is_screen) {
559 int trans_ctrl = [video_device transportControlsSupported];
560 AVCaptureDeviceTransportControlsPlaybackMode trans_mode = [video_device transportControlsPlaybackMode];
563 ctx->observed_mode = trans_mode;
564 ctx->observed_device = video_device;
571 queue = dispatch_queue_create(
"avf_queue",
NULL);
572 [ctx->video_output setSampleBufferDelegate:ctx->avf_delegate queue:queue];
573 dispatch_release(queue);
575 if ([
ctx->capture_session canAddOutput:
ctx->video_output]) {
576 [ctx->capture_session addOutput:ctx->video_output];
588 NSError *
error = nil;
589 AVCaptureDeviceInput* audio_dev_input = [[[AVCaptureDeviceInput alloc] initWithDevice:audio_device
error:&
error] autorelease];
590 dispatch_queue_t queue;
592 if (!audio_dev_input) {
594 [[
error localizedDescription] UTF8String]);
598 if ([
ctx->capture_session canAddInput:audio_dev_input]) {
599 [ctx->capture_session addInput:audio_dev_input];
606 ctx->audio_output = [[AVCaptureAudioDataOutput alloc] init];
608 if (!
ctx->audio_output) {
615 queue = dispatch_queue_create(
"avf_audio_queue",
NULL);
616 [ctx->audio_output setSampleBufferDelegate:ctx->avf_audio_delegate queue:queue];
617 dispatch_release(queue);
619 if ([
ctx->capture_session canAddOutput:
ctx->audio_output]) {
620 [ctx->capture_session addOutput:ctx->audio_output];
632 CVImageBufferRef image_buffer;
633 CMBlockBufferRef block_buffer;
634 CGSize image_buffer_size;
642 while (
ctx->frames_captured < 1) {
643 CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, YES);
648 ctx->video_stream_index = stream->index;
652 image_buffer = CMSampleBufferGetImageBuffer(
ctx->current_frame);
653 block_buffer = CMSampleBufferGetDataBuffer(
ctx->current_frame);
656 image_buffer_size = CVImageBufferGetEncodedSize(image_buffer);
660 stream->codecpar->width = (
int)image_buffer_size.width;
661 stream->codecpar->height = (
int)image_buffer_size.height;
662 stream->codecpar->format =
ctx->pixel_format;
666 stream->codecpar->format =
ctx->pixel_format;
669 CFRelease(
ctx->current_frame);
670 ctx->current_frame = nil;
680 CMFormatDescriptionRef format_desc;
688 while (
ctx->audio_frames_captured < 1) {
689 CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, YES);
694 ctx->audio_stream_index = stream->index;
698 format_desc = CMSampleBufferGetFormatDescription(
ctx->current_audio_frame);
699 const AudioStreamBasicDescription *basic_desc = CMAudioFormatDescriptionGetStreamBasicDescription(format_desc);
708 stream->codecpar->sample_rate = basic_desc->mSampleRate;
711 ctx->audio_channels = basic_desc->mChannelsPerFrame;
712 ctx->audio_bits_per_sample = basic_desc->mBitsPerChannel;
713 ctx->audio_float = basic_desc->mFormatFlags & kAudioFormatFlagIsFloat;
714 ctx->audio_be = basic_desc->mFormatFlags & kAudioFormatFlagIsBigEndian;
715 ctx->audio_signed_integer = basic_desc->mFormatFlags & kAudioFormatFlagIsSignedInteger;
716 ctx->audio_packed = basic_desc->mFormatFlags & kAudioFormatFlagIsPacked;
717 ctx->audio_non_interleaved = basic_desc->mFormatFlags & kAudioFormatFlagIsNonInterleaved;
719 if (basic_desc->mFormatID == kAudioFormatLinearPCM &&
721 ctx->audio_bits_per_sample == 32 &&
724 }
else if (basic_desc->mFormatID == kAudioFormatLinearPCM &&
725 ctx->audio_signed_integer &&
726 ctx->audio_bits_per_sample == 16 &&
729 }
else if (basic_desc->mFormatID == kAudioFormatLinearPCM &&
730 ctx->audio_signed_integer &&
731 ctx->audio_bits_per_sample == 24 &&
734 }
else if (basic_desc->mFormatID == kAudioFormatLinearPCM &&
735 ctx->audio_signed_integer &&
736 ctx->audio_bits_per_sample == 32 &&
745 if (
ctx->audio_non_interleaved) {
746 CMBlockBufferRef block_buffer = CMSampleBufferGetDataBuffer(
ctx->current_audio_frame);
747 ctx->audio_buffer_size = CMBlockBufferGetDataLength(block_buffer);
749 if (!
ctx->audio_buffer) {
756 CFRelease(
ctx->current_audio_frame);
757 ctx->current_audio_frame = nil;
767 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
768 uint32_t num_screens = 0;
770 AVCaptureDevice *video_device = nil;
771 AVCaptureDevice *audio_device = nil;
773 NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
774 NSArray *devices_muxed = [AVCaptureDevice devicesWithMediaType:AVMediaTypeMuxed];
776 ctx->num_video_devices = [devices count] + [devices_muxed count];
780 #if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
781 CGGetActiveDisplayList(0,
NULL, &num_screens);
785 if (
ctx->list_devices) {
788 for (AVCaptureDevice *device in devices) {
789 const char *
name = [[device localizedName] UTF8String];
790 index = [devices indexOfObject:device];
793 for (AVCaptureDevice *device in devices_muxed) {
794 const char *
name = [[device localizedName] UTF8String];
795 index = [devices count] + [devices_muxed indexOfObject:device];
798 #if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
799 if (num_screens > 0) {
800 CGDirectDisplayID screens[num_screens];
801 CGGetActiveDisplayList(num_screens, screens, &num_screens);
802 for (
int i = 0;
i < num_screens;
i++) {
809 devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeAudio];
810 for (AVCaptureDevice *device in devices) {
811 const char *
name = [[device localizedName] UTF8String];
812 int index = [devices indexOfObject:device];
824 if (
ctx->video_device_index == -1 &&
ctx->video_filename) {
825 sscanf(
ctx->video_filename,
"%d", &
ctx->video_device_index);
827 if (
ctx->audio_device_index == -1 &&
ctx->audio_filename) {
828 sscanf(
ctx->audio_filename,
"%d", &
ctx->audio_device_index);
831 if (
ctx->video_device_index >= 0) {
832 if (
ctx->video_device_index <
ctx->num_video_devices) {
833 if (
ctx->video_device_index < [devices count]) {
834 video_device = [devices objectAtIndex:ctx->video_device_index];
836 video_device = [devices_muxed objectAtIndex:(ctx->video_device_index - [devices count])];
837 ctx->video_is_muxed = 1;
839 }
else if (
ctx->video_device_index <
ctx->num_video_devices + num_screens) {
840 #if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
841 CGDirectDisplayID screens[num_screens];
842 CGGetActiveDisplayList(num_screens, screens, &num_screens);
843 AVCaptureScreenInput* capture_screen_input = [[[AVCaptureScreenInput alloc] initWithDisplayID:screens[ctx->video_device_index - ctx->
num_video_devices]] autorelease];
845 if (
ctx->framerate.num > 0) {
846 capture_screen_input.minFrameDuration = CMTimeMake(
ctx->framerate.den,
ctx->framerate.num);
849 #if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1080
850 if (
ctx->capture_cursor) {
851 capture_screen_input.capturesCursor = YES;
853 capture_screen_input.capturesCursor = NO;
857 if (
ctx->capture_mouse_clicks) {
858 capture_screen_input.capturesMouseClicks = YES;
860 capture_screen_input.capturesMouseClicks = NO;
863 video_device = (AVCaptureDevice*) capture_screen_input;
864 ctx->video_is_screen = 1;
870 }
else if (
ctx->video_filename &&
871 strncmp(
ctx->video_filename,
"none", 4)) {
872 if (!strncmp(
ctx->video_filename,
"default", 7)) {
873 video_device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
876 for (AVCaptureDevice *device in devices) {
877 if (!strncmp(
ctx->video_filename, [[device localizedName] UTF8String], strlen(
ctx->video_filename))) {
878 video_device = device;
883 for (AVCaptureDevice *device in devices_muxed) {
884 if (!strncmp(
ctx->video_filename, [[device localizedName] UTF8String], strlen(
ctx->video_filename))) {
885 video_device = device;
886 ctx->video_is_muxed = 1;
891 #if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
895 if(sscanf(
ctx->video_filename,
"Capture screen %d", &idx) && idx < num_screens) {
896 CGDirectDisplayID screens[num_screens];
897 CGGetActiveDisplayList(num_screens, screens, &num_screens);
898 AVCaptureScreenInput* capture_screen_input = [[[AVCaptureScreenInput alloc] initWithDisplayID:screens[idx]] autorelease];
899 video_device = (AVCaptureDevice*) capture_screen_input;
900 ctx->video_device_index =
ctx->num_video_devices + idx;
901 ctx->video_is_screen = 1;
903 if (
ctx->framerate.num > 0) {
904 capture_screen_input.minFrameDuration = CMTimeMake(
ctx->framerate.den,
ctx->framerate.num);
907 #if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1080
908 if (
ctx->capture_cursor) {
909 capture_screen_input.capturesCursor = YES;
911 capture_screen_input.capturesCursor = NO;
915 if (
ctx->capture_mouse_clicks) {
916 capture_screen_input.capturesMouseClicks = YES;
918 capture_screen_input.capturesMouseClicks = NO;
932 if (
ctx->audio_device_index >= 0) {
933 NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeAudio];
935 if (
ctx->audio_device_index >= [devices count]) {
940 audio_device = [devices objectAtIndex:ctx->audio_device_index];
941 }
else if (
ctx->audio_filename &&
942 strncmp(
ctx->audio_filename,
"none", 4)) {
943 if (!strncmp(
ctx->audio_filename,
"default", 7)) {
944 audio_device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeAudio];
946 NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeAudio];
948 for (AVCaptureDevice *device in devices) {
949 if (!strncmp(
ctx->audio_filename, [[device localizedName] UTF8String], strlen(
ctx->audio_filename))) {
950 audio_device = device;
963 if (!video_device && !audio_device) {
969 if (
ctx->video_device_index <
ctx->num_video_devices) {
976 av_log(
s,
AV_LOG_DEBUG,
"audio device '%s' opened\n", [[audio_device localizedName] UTF8String]);
980 ctx->capture_session = [[AVCaptureSession alloc] init];
988 [ctx->capture_session startRunning];
992 if (!
ctx->video_is_screen) {
993 [video_device unlockForConfiguration];
1017 CVPixelBufferRef image_buffer,
1021 int src_linesize[4];
1022 const uint8_t *src_data[4];
1023 int width = CVPixelBufferGetWidth(image_buffer);
1024 int height = CVPixelBufferGetHeight(image_buffer);
1027 memset(src_linesize, 0,
sizeof(src_linesize));
1028 memset(src_data, 0,
sizeof(src_data));
1030 status = CVPixelBufferLockBaseAddress(image_buffer, 0);
1031 if (
status != kCVReturnSuccess) {
1036 if (CVPixelBufferIsPlanar(image_buffer)) {
1037 size_t plane_count = CVPixelBufferGetPlaneCount(image_buffer);
1039 for(
i = 0;
i < plane_count;
i++){
1040 src_linesize[i] = CVPixelBufferGetBytesPerRowOfPlane(image_buffer,
i);
1041 src_data[i] = CVPixelBufferGetBaseAddressOfPlane(image_buffer,
i);
1044 src_linesize[0] = CVPixelBufferGetBytesPerRow(image_buffer);
1045 src_data[0] = CVPixelBufferGetBaseAddress(image_buffer);
1049 src_data, src_linesize,
1054 CVPixelBufferUnlockBaseAddress(image_buffer, 0);
1064 CVImageBufferRef image_buffer;
1065 CMBlockBufferRef block_buffer;
1068 if (
ctx->current_frame != nil) {
1072 image_buffer = CMSampleBufferGetImageBuffer(
ctx->current_frame);
1073 block_buffer = CMSampleBufferGetDataBuffer(
ctx->current_frame);
1075 if (image_buffer != nil) {
1076 length = (
int)CVPixelBufferGetDataSize(image_buffer);
1077 }
else if (block_buffer != nil) {
1078 length = (
int)CMBlockBufferGetDataLength(block_buffer);
1092 if (CMSampleBufferGetOutputSampleTimingInfoArray(
ctx->current_frame, 1, &
timing_info, &count) == noErr) {
1104 OSStatus
ret = CMBlockBufferCopyDataBytes(block_buffer, 0,
pkt->
size,
pkt->
data);
1105 if (
ret != kCMBlockBufferNoErr) {
1109 CFRelease(
ctx->current_frame);
1110 ctx->current_frame = nil;
1116 }
else if (
ctx->current_audio_frame != nil) {
1117 CMBlockBufferRef block_buffer = CMSampleBufferGetDataBuffer(
ctx->current_audio_frame);
1118 int block_buffer_size = CMBlockBufferGetDataLength(block_buffer);
1120 if (!block_buffer || !block_buffer_size) {
1125 if (
ctx->audio_non_interleaved && block_buffer_size >
ctx->audio_buffer_size) {
1138 if (CMSampleBufferGetOutputSampleTimingInfoArray(
ctx->current_audio_frame, 1, &
timing_info, &count) == noErr) {
1146 if (
ctx->audio_non_interleaved) {
1149 OSStatus
ret = CMBlockBufferCopyDataBytes(block_buffer, 0,
pkt->
size,
ctx->audio_buffer);
1150 if (
ret != kCMBlockBufferNoErr) {
1155 num_samples =
pkt->
size / (
ctx->audio_channels * (
ctx->audio_bits_per_sample >> 3));
1158 #define INTERLEAVE_OUTPUT(bps) \
1160 int##bps##_t **src; \
1161 int##bps##_t *dest; \
1162 src = av_malloc(ctx->audio_channels * sizeof(int##bps##_t*)); \
1164 unlock_frames(ctx); \
1165 return AVERROR(EIO); \
1168 for (c = 0; c < ctx->audio_channels; c++) { \
1169 src[c] = ((int##bps##_t*)ctx->audio_buffer) + c * num_samples; \
1171 dest = (int##bps##_t*)pkt->data; \
1172 shift = bps - ctx->audio_bits_per_sample; \
1173 for (sample = 0; sample < num_samples; sample++) \
1174 for (c = 0; c < ctx->audio_channels; c++) \
1175 *dest++ = src[c][sample] << shift; \
1179 if (
ctx->audio_bits_per_sample <= 16) {
1185 OSStatus
ret = CMBlockBufferCopyDataBytes(block_buffer, 0,
pkt->
size,
pkt->
data);
1186 if (
ret != kCMBlockBufferNoErr) {
1192 CFRelease(
ctx->current_audio_frame);
1193 ctx->current_audio_frame = nil;
1197 if (
ctx->observed_quit) {
1241 .
name =
"avfoundation",