You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

854 lines
30KB

  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. * @file
  23. * AVFoundation input device
  24. * @author Thilo Borgmann <thilo.borgmann@mail.de>
  25. */
  26. #import <AVFoundation/AVFoundation.h>
  27. #include <pthread.h>
  28. #include "libavutil/pixdesc.h"
  29. #include "libavutil/opt.h"
  30. #include "libavutil/avstring.h"
  31. #include "libavformat/internal.h"
  32. #include "libavutil/internal.h"
  33. #include "libavutil/time.h"
  34. #include "avdevice.h"
  35. static const int avf_time_base = 1000000;
  36. static const AVRational avf_time_base_q = {
  37. .num = 1,
  38. .den = avf_time_base
  39. };
  40. struct AVFPixelFormatSpec {
  41. enum AVPixelFormat ff_id;
  42. OSType avf_id;
  43. };
  44. static const struct AVFPixelFormatSpec avf_pixel_formats[] = {
  45. { AV_PIX_FMT_MONOBLACK, kCVPixelFormatType_1Monochrome },
  46. { AV_PIX_FMT_RGB555BE, kCVPixelFormatType_16BE555 },
  47. { AV_PIX_FMT_RGB555LE, kCVPixelFormatType_16LE555 },
  48. { AV_PIX_FMT_RGB565BE, kCVPixelFormatType_16BE565 },
  49. { AV_PIX_FMT_RGB565LE, kCVPixelFormatType_16LE565 },
  50. { AV_PIX_FMT_RGB24, kCVPixelFormatType_24RGB },
  51. { AV_PIX_FMT_BGR24, kCVPixelFormatType_24BGR },
  52. { AV_PIX_FMT_0RGB, kCVPixelFormatType_32ARGB },
  53. { AV_PIX_FMT_BGR0, kCVPixelFormatType_32BGRA },
  54. { AV_PIX_FMT_0BGR, kCVPixelFormatType_32ABGR },
  55. { AV_PIX_FMT_RGB0, kCVPixelFormatType_32RGBA },
  56. { AV_PIX_FMT_BGR48BE, kCVPixelFormatType_48RGB },
  57. { AV_PIX_FMT_UYVY422, kCVPixelFormatType_422YpCbCr8 },
  58. { AV_PIX_FMT_YUVA444P, kCVPixelFormatType_4444YpCbCrA8R },
  59. { AV_PIX_FMT_YUVA444P16LE, kCVPixelFormatType_4444AYpCbCr16 },
  60. { AV_PIX_FMT_YUV444P, kCVPixelFormatType_444YpCbCr8 },
  61. { AV_PIX_FMT_YUV422P16, kCVPixelFormatType_422YpCbCr16 },
  62. { AV_PIX_FMT_YUV422P10, kCVPixelFormatType_422YpCbCr10 },
  63. { AV_PIX_FMT_YUV444P10, kCVPixelFormatType_444YpCbCr10 },
  64. { AV_PIX_FMT_YUV420P, kCVPixelFormatType_420YpCbCr8Planar },
  65. { AV_PIX_FMT_NV12, kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange },
  66. { AV_PIX_FMT_YUYV422, kCVPixelFormatType_422YpCbCr8_yuvs },
  67. #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1080
  68. { AV_PIX_FMT_GRAY8, kCVPixelFormatType_OneComponent8 },
  69. #endif
  70. { AV_PIX_FMT_NONE, 0 }
  71. };
  72. typedef struct
  73. {
  74. AVClass* class;
  75. float frame_rate;
  76. int frames_captured;
  77. int audio_frames_captured;
  78. int64_t first_pts;
  79. int64_t first_audio_pts;
  80. pthread_mutex_t frame_lock;
  81. pthread_cond_t frame_wait_cond;
  82. id avf_delegate;
  83. id avf_audio_delegate;
  84. int list_devices;
  85. int video_device_index;
  86. int video_stream_index;
  87. int audio_device_index;
  88. int audio_stream_index;
  89. char *video_filename;
  90. char *audio_filename;
  91. int num_video_devices;
  92. int audio_channels;
  93. int audio_bits_per_sample;
  94. int audio_float;
  95. int audio_be;
  96. int audio_signed_integer;
  97. int audio_packed;
  98. int audio_non_interleaved;
  99. int32_t *audio_buffer;
  100. int audio_buffer_size;
  101. enum AVPixelFormat pixel_format;
  102. AVCaptureSession *capture_session;
  103. AVCaptureVideoDataOutput *video_output;
  104. AVCaptureAudioDataOutput *audio_output;
  105. CMSampleBufferRef current_frame;
  106. CMSampleBufferRef current_audio_frame;
  107. } AVFContext;
  108. static void lock_frames(AVFContext* ctx)
  109. {
  110. pthread_mutex_lock(&ctx->frame_lock);
  111. }
  112. static void unlock_frames(AVFContext* ctx)
  113. {
  114. pthread_mutex_unlock(&ctx->frame_lock);
  115. }
  116. /** FrameReciever class - delegate for AVCaptureSession
  117. */
  118. @interface AVFFrameReceiver : NSObject
  119. {
  120. AVFContext* _context;
  121. }
  122. - (id)initWithContext:(AVFContext*)context;
  123. - (void) captureOutput:(AVCaptureOutput *)captureOutput
  124. didOutputSampleBuffer:(CMSampleBufferRef)videoFrame
  125. fromConnection:(AVCaptureConnection *)connection;
  126. @end
  127. @implementation AVFFrameReceiver
  128. - (id)initWithContext:(AVFContext*)context
  129. {
  130. if (self = [super init]) {
  131. _context = context;
  132. }
  133. return self;
  134. }
  135. - (void) captureOutput:(AVCaptureOutput *)captureOutput
  136. didOutputSampleBuffer:(CMSampleBufferRef)videoFrame
  137. fromConnection:(AVCaptureConnection *)connection
  138. {
  139. lock_frames(_context);
  140. if (_context->current_frame != nil) {
  141. CFRelease(_context->current_frame);
  142. }
  143. _context->current_frame = (CMSampleBufferRef)CFRetain(videoFrame);
  144. pthread_cond_signal(&_context->frame_wait_cond);
  145. unlock_frames(_context);
  146. ++_context->frames_captured;
  147. }
  148. @end
  149. /** AudioReciever class - delegate for AVCaptureSession
  150. */
  151. @interface AVFAudioReceiver : NSObject
  152. {
  153. AVFContext* _context;
  154. }
  155. - (id)initWithContext:(AVFContext*)context;
  156. - (void) captureOutput:(AVCaptureOutput *)captureOutput
  157. didOutputSampleBuffer:(CMSampleBufferRef)audioFrame
  158. fromConnection:(AVCaptureConnection *)connection;
  159. @end
  160. @implementation AVFAudioReceiver
  161. - (id)initWithContext:(AVFContext*)context
  162. {
  163. if (self = [super init]) {
  164. _context = context;
  165. }
  166. return self;
  167. }
  168. - (void) captureOutput:(AVCaptureOutput *)captureOutput
  169. didOutputSampleBuffer:(CMSampleBufferRef)audioFrame
  170. fromConnection:(AVCaptureConnection *)connection
  171. {
  172. lock_frames(_context);
  173. if (_context->current_audio_frame != nil) {
  174. CFRelease(_context->current_audio_frame);
  175. }
  176. _context->current_audio_frame = (CMSampleBufferRef)CFRetain(audioFrame);
  177. pthread_cond_signal(&_context->frame_wait_cond);
  178. unlock_frames(_context);
  179. ++_context->audio_frames_captured;
  180. }
  181. @end
  182. static void destroy_context(AVFContext* ctx)
  183. {
  184. [ctx->capture_session stopRunning];
  185. [ctx->capture_session release];
  186. [ctx->video_output release];
  187. [ctx->audio_output release];
  188. [ctx->avf_delegate release];
  189. [ctx->avf_audio_delegate release];
  190. ctx->capture_session = NULL;
  191. ctx->video_output = NULL;
  192. ctx->audio_output = NULL;
  193. ctx->avf_delegate = NULL;
  194. ctx->avf_audio_delegate = NULL;
  195. av_freep(&ctx->audio_buffer);
  196. pthread_mutex_destroy(&ctx->frame_lock);
  197. pthread_cond_destroy(&ctx->frame_wait_cond);
  198. if (ctx->current_frame) {
  199. CFRelease(ctx->current_frame);
  200. }
  201. }
  202. static void parse_device_name(AVFormatContext *s)
  203. {
  204. AVFContext *ctx = (AVFContext*)s->priv_data;
  205. char *tmp = av_strdup(s->filename);
  206. char *save;
  207. if (tmp[0] != ':') {
  208. ctx->video_filename = av_strtok(tmp, ":", &save);
  209. ctx->audio_filename = av_strtok(NULL, ":", &save);
  210. } else {
  211. ctx->audio_filename = av_strtok(tmp, ":", &save);
  212. }
  213. }
  214. static int add_video_device(AVFormatContext *s, AVCaptureDevice *video_device)
  215. {
  216. AVFContext *ctx = (AVFContext*)s->priv_data;
  217. NSError *error = nil;
  218. AVCaptureInput* capture_input = nil;
  219. if (ctx->video_device_index < ctx->num_video_devices) {
  220. capture_input = (AVCaptureInput*) [[[AVCaptureDeviceInput alloc] initWithDevice:video_device error:&error] autorelease];
  221. } else {
  222. capture_input = (AVCaptureInput*) video_device;
  223. }
  224. if (!capture_input) {
  225. av_log(s, AV_LOG_ERROR, "Failed to create AV capture input device: %s\n",
  226. [[error localizedDescription] UTF8String]);
  227. return 1;
  228. }
  229. if ([ctx->capture_session canAddInput:capture_input]) {
  230. [ctx->capture_session addInput:capture_input];
  231. } else {
  232. av_log(s, AV_LOG_ERROR, "can't add video input to capture session\n");
  233. return 1;
  234. }
  235. // Attaching output
  236. ctx->video_output = [[AVCaptureVideoDataOutput alloc] init];
  237. if (!ctx->video_output) {
  238. av_log(s, AV_LOG_ERROR, "Failed to init AV video output\n");
  239. return 1;
  240. }
  241. // select pixel format
  242. struct AVFPixelFormatSpec pxl_fmt_spec;
  243. pxl_fmt_spec.ff_id = AV_PIX_FMT_NONE;
  244. for (int i = 0; avf_pixel_formats[i].ff_id != AV_PIX_FMT_NONE; i++) {
  245. if (ctx->pixel_format == avf_pixel_formats[i].ff_id) {
  246. pxl_fmt_spec = avf_pixel_formats[i];
  247. break;
  248. }
  249. }
  250. // check if selected pixel format is supported by AVFoundation
  251. if (pxl_fmt_spec.ff_id == AV_PIX_FMT_NONE) {
  252. av_log(s, AV_LOG_ERROR, "Selected pixel format (%s) is not supported by AVFoundation.\n",
  253. av_get_pix_fmt_name(pxl_fmt_spec.ff_id));
  254. return 1;
  255. }
  256. // check if the pixel format is available for this device
  257. if ([[ctx->video_output availableVideoCVPixelFormatTypes] indexOfObject:[NSNumber numberWithInt:pxl_fmt_spec.avf_id]] == NSNotFound) {
  258. av_log(s, AV_LOG_ERROR, "Selected pixel format (%s) is not supported by the input device.\n",
  259. av_get_pix_fmt_name(pxl_fmt_spec.ff_id));
  260. pxl_fmt_spec.ff_id = AV_PIX_FMT_NONE;
  261. av_log(s, AV_LOG_ERROR, "Supported pixel formats:\n");
  262. for (NSNumber *pxl_fmt in [ctx->video_output availableVideoCVPixelFormatTypes]) {
  263. struct AVFPixelFormatSpec pxl_fmt_dummy;
  264. pxl_fmt_dummy.ff_id = AV_PIX_FMT_NONE;
  265. for (int i = 0; avf_pixel_formats[i].ff_id != AV_PIX_FMT_NONE; i++) {
  266. if ([pxl_fmt intValue] == avf_pixel_formats[i].avf_id) {
  267. pxl_fmt_dummy = avf_pixel_formats[i];
  268. break;
  269. }
  270. }
  271. if (pxl_fmt_dummy.ff_id != AV_PIX_FMT_NONE) {
  272. av_log(s, AV_LOG_ERROR, " %s\n", av_get_pix_fmt_name(pxl_fmt_dummy.ff_id));
  273. // select first supported pixel format instead of user selected (or default) pixel format
  274. if (pxl_fmt_spec.ff_id == AV_PIX_FMT_NONE) {
  275. pxl_fmt_spec = pxl_fmt_dummy;
  276. }
  277. }
  278. }
  279. // fail if there is no appropriate pixel format or print a warning about overriding the pixel format
  280. if (pxl_fmt_spec.ff_id == AV_PIX_FMT_NONE) {
  281. return 1;
  282. } else {
  283. av_log(s, AV_LOG_WARNING, "Overriding selected pixel format to use %s instead.\n",
  284. av_get_pix_fmt_name(pxl_fmt_spec.ff_id));
  285. }
  286. }
  287. ctx->pixel_format = pxl_fmt_spec.ff_id;
  288. NSNumber *pixel_format = [NSNumber numberWithUnsignedInt:pxl_fmt_spec.avf_id];
  289. NSDictionary *capture_dict = [NSDictionary dictionaryWithObject:pixel_format
  290. forKey:(id)kCVPixelBufferPixelFormatTypeKey];
  291. [ctx->video_output setVideoSettings:capture_dict];
  292. [ctx->video_output setAlwaysDiscardsLateVideoFrames:YES];
  293. ctx->avf_delegate = [[AVFFrameReceiver alloc] initWithContext:ctx];
  294. dispatch_queue_t queue = dispatch_queue_create("avf_queue", NULL);
  295. [ctx->video_output setSampleBufferDelegate:ctx->avf_delegate queue:queue];
  296. dispatch_release(queue);
  297. if ([ctx->capture_session canAddOutput:ctx->video_output]) {
  298. [ctx->capture_session addOutput:ctx->video_output];
  299. } else {
  300. av_log(s, AV_LOG_ERROR, "can't add video output to capture session\n");
  301. return 1;
  302. }
  303. return 0;
  304. }
  305. static int add_audio_device(AVFormatContext *s, AVCaptureDevice *audio_device)
  306. {
  307. AVFContext *ctx = (AVFContext*)s->priv_data;
  308. NSError *error = nil;
  309. AVCaptureDeviceInput* audio_dev_input = [[[AVCaptureDeviceInput alloc] initWithDevice:audio_device error:&error] autorelease];
  310. if (!audio_dev_input) {
  311. av_log(s, AV_LOG_ERROR, "Failed to create AV capture input device: %s\n",
  312. [[error localizedDescription] UTF8String]);
  313. return 1;
  314. }
  315. if ([ctx->capture_session canAddInput:audio_dev_input]) {
  316. [ctx->capture_session addInput:audio_dev_input];
  317. } else {
  318. av_log(s, AV_LOG_ERROR, "can't add audio input to capture session\n");
  319. return 1;
  320. }
  321. // Attaching output
  322. ctx->audio_output = [[AVCaptureAudioDataOutput alloc] init];
  323. if (!ctx->audio_output) {
  324. av_log(s, AV_LOG_ERROR, "Failed to init AV audio output\n");
  325. return 1;
  326. }
  327. ctx->avf_audio_delegate = [[AVFAudioReceiver alloc] initWithContext:ctx];
  328. dispatch_queue_t queue = dispatch_queue_create("avf_audio_queue", NULL);
  329. [ctx->audio_output setSampleBufferDelegate:ctx->avf_audio_delegate queue:queue];
  330. dispatch_release(queue);
  331. if ([ctx->capture_session canAddOutput:ctx->audio_output]) {
  332. [ctx->capture_session addOutput:ctx->audio_output];
  333. } else {
  334. av_log(s, AV_LOG_ERROR, "adding audio output to capture session failed\n");
  335. return 1;
  336. }
  337. return 0;
  338. }
  339. static int get_video_config(AVFormatContext *s)
  340. {
  341. AVFContext *ctx = (AVFContext*)s->priv_data;
  342. // Take stream info from the first frame.
  343. while (ctx->frames_captured < 1) {
  344. CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, YES);
  345. }
  346. lock_frames(ctx);
  347. AVStream* stream = avformat_new_stream(s, NULL);
  348. if (!stream) {
  349. return 1;
  350. }
  351. ctx->video_stream_index = stream->index;
  352. avpriv_set_pts_info(stream, 64, 1, avf_time_base);
  353. CVImageBufferRef image_buffer = CMSampleBufferGetImageBuffer(ctx->current_frame);
  354. CGSize image_buffer_size = CVImageBufferGetEncodedSize(image_buffer);
  355. stream->codec->codec_id = AV_CODEC_ID_RAWVIDEO;
  356. stream->codec->codec_type = AVMEDIA_TYPE_VIDEO;
  357. stream->codec->width = (int)image_buffer_size.width;
  358. stream->codec->height = (int)image_buffer_size.height;
  359. stream->codec->pix_fmt = ctx->pixel_format;
  360. CFRelease(ctx->current_frame);
  361. ctx->current_frame = nil;
  362. unlock_frames(ctx);
  363. return 0;
  364. }
  365. static int get_audio_config(AVFormatContext *s)
  366. {
  367. AVFContext *ctx = (AVFContext*)s->priv_data;
  368. // Take stream info from the first frame.
  369. while (ctx->audio_frames_captured < 1) {
  370. CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, YES);
  371. }
  372. lock_frames(ctx);
  373. AVStream* stream = avformat_new_stream(s, NULL);
  374. if (!stream) {
  375. return 1;
  376. }
  377. ctx->audio_stream_index = stream->index;
  378. avpriv_set_pts_info(stream, 64, 1, avf_time_base);
  379. CMFormatDescriptionRef format_desc = CMSampleBufferGetFormatDescription(ctx->current_audio_frame);
  380. const AudioStreamBasicDescription *basic_desc = CMAudioFormatDescriptionGetStreamBasicDescription(format_desc);
  381. if (!basic_desc) {
  382. av_log(s, AV_LOG_ERROR, "audio format not available\n");
  383. return 1;
  384. }
  385. stream->codec->codec_type = AVMEDIA_TYPE_AUDIO;
  386. stream->codec->sample_rate = basic_desc->mSampleRate;
  387. stream->codec->channels = basic_desc->mChannelsPerFrame;
  388. stream->codec->channel_layout = av_get_default_channel_layout(stream->codec->channels);
  389. ctx->audio_channels = basic_desc->mChannelsPerFrame;
  390. ctx->audio_bits_per_sample = basic_desc->mBitsPerChannel;
  391. ctx->audio_float = basic_desc->mFormatFlags & kAudioFormatFlagIsFloat;
  392. ctx->audio_be = basic_desc->mFormatFlags & kAudioFormatFlagIsBigEndian;
  393. ctx->audio_signed_integer = basic_desc->mFormatFlags & kAudioFormatFlagIsSignedInteger;
  394. ctx->audio_packed = basic_desc->mFormatFlags & kAudioFormatFlagIsPacked;
  395. ctx->audio_non_interleaved = basic_desc->mFormatFlags & kAudioFormatFlagIsNonInterleaved;
  396. if (basic_desc->mFormatID == kAudioFormatLinearPCM &&
  397. ctx->audio_float &&
  398. ctx->audio_packed) {
  399. stream->codec->codec_id = ctx->audio_be ? AV_CODEC_ID_PCM_F32BE : AV_CODEC_ID_PCM_F32LE;
  400. } else {
  401. av_log(s, AV_LOG_ERROR, "audio format is not supported\n");
  402. return 1;
  403. }
  404. if (ctx->audio_non_interleaved) {
  405. CMBlockBufferRef block_buffer = CMSampleBufferGetDataBuffer(ctx->current_audio_frame);
  406. ctx->audio_buffer_size = CMBlockBufferGetDataLength(block_buffer);
  407. ctx->audio_buffer = av_malloc(ctx->audio_buffer_size);
  408. if (!ctx->audio_buffer) {
  409. av_log(s, AV_LOG_ERROR, "error allocating audio buffer\n");
  410. return 1;
  411. }
  412. }
  413. CFRelease(ctx->current_audio_frame);
  414. ctx->current_audio_frame = nil;
  415. unlock_frames(ctx);
  416. return 0;
  417. }
  418. static int avf_read_header(AVFormatContext *s)
  419. {
  420. NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
  421. AVFContext *ctx = (AVFContext*)s->priv_data;
  422. ctx->first_pts = av_gettime();
  423. ctx->first_audio_pts = av_gettime();
  424. uint32_t num_screens = 0;
  425. pthread_mutex_init(&ctx->frame_lock, NULL);
  426. pthread_cond_init(&ctx->frame_wait_cond, NULL);
  427. #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
  428. CGGetActiveDisplayList(0, NULL, &num_screens);
  429. #endif
  430. // List devices if requested
  431. if (ctx->list_devices) {
  432. av_log(ctx, AV_LOG_INFO, "AVFoundation video devices:\n");
  433. NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
  434. int index = 0;
  435. for (AVCaptureDevice *device in devices) {
  436. const char *name = [[device localizedName] UTF8String];
  437. index = [devices indexOfObject:device];
  438. av_log(ctx, AV_LOG_INFO, "[%d] %s\n", index, name);
  439. index++;
  440. }
  441. #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
  442. if (num_screens > 0) {
  443. CGDirectDisplayID screens[num_screens];
  444. CGGetActiveDisplayList(num_screens, screens, &num_screens);
  445. for (int i = 0; i < num_screens; i++) {
  446. av_log(ctx, AV_LOG_INFO, "[%d] Capture screen %d\n", index + i, i);
  447. }
  448. }
  449. #endif
  450. av_log(ctx, AV_LOG_INFO, "AVFoundation audio devices:\n");
  451. devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeAudio];
  452. for (AVCaptureDevice *device in devices) {
  453. const char *name = [[device localizedName] UTF8String];
  454. int index = [devices indexOfObject:device];
  455. av_log(ctx, AV_LOG_INFO, "[%d] %s\n", index, name);
  456. }
  457. goto fail;
  458. }
  459. // Find capture device
  460. AVCaptureDevice *video_device = nil;
  461. AVCaptureDevice *audio_device = nil;
  462. NSArray *video_devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
  463. ctx->num_video_devices = [video_devices count];
  464. // parse input filename for video and audio device
  465. parse_device_name(s);
  466. // check for device index given in filename
  467. if (ctx->video_device_index == -1 && ctx->video_filename) {
  468. sscanf(ctx->video_filename, "%d", &ctx->video_device_index);
  469. }
  470. if (ctx->audio_device_index == -1 && ctx->audio_filename) {
  471. sscanf(ctx->audio_filename, "%d", &ctx->audio_device_index);
  472. }
  473. if (ctx->video_device_index >= 0) {
  474. if (ctx->video_device_index < ctx->num_video_devices) {
  475. video_device = [video_devices objectAtIndex:ctx->video_device_index];
  476. } else if (ctx->video_device_index < ctx->num_video_devices + num_screens) {
  477. #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
  478. CGDirectDisplayID screens[num_screens];
  479. CGGetActiveDisplayList(num_screens, screens, &num_screens);
  480. AVCaptureScreenInput* capture_screen_input = [[[AVCaptureScreenInput alloc] initWithDisplayID:screens[ctx->video_device_index - ctx->num_video_devices]] autorelease];
  481. video_device = (AVCaptureDevice*) capture_screen_input;
  482. #endif
  483. } else {
  484. av_log(ctx, AV_LOG_ERROR, "Invalid device index\n");
  485. goto fail;
  486. }
  487. } else if (ctx->video_filename &&
  488. strncmp(ctx->video_filename, "default", 7)) {
  489. // looking for video inputs
  490. for (AVCaptureDevice *device in video_devices) {
  491. if (!strncmp(ctx->video_filename, [[device localizedName] UTF8String], strlen(ctx->video_filename))) {
  492. video_device = device;
  493. break;
  494. }
  495. }
  496. #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
  497. // looking for screen inputs
  498. if (!video_device) {
  499. int idx;
  500. if(sscanf(ctx->video_filename, "Capture screen %d", &idx) && idx < num_screens) {
  501. CGDirectDisplayID screens[num_screens];
  502. CGGetActiveDisplayList(num_screens, screens, &num_screens);
  503. AVCaptureScreenInput* capture_screen_input = [[[AVCaptureScreenInput alloc] initWithDisplayID:screens[idx]] autorelease];
  504. video_device = (AVCaptureDevice*) capture_screen_input;
  505. ctx->video_device_index = ctx->num_video_devices + idx;
  506. }
  507. }
  508. #endif
  509. if (!video_device) {
  510. av_log(ctx, AV_LOG_ERROR, "Video device not found\n");
  511. goto fail;
  512. }
  513. } else {
  514. video_device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
  515. }
  516. // get audio device
  517. if (ctx->audio_device_index >= 0) {
  518. NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeAudio];
  519. if (ctx->audio_device_index >= [devices count]) {
  520. av_log(ctx, AV_LOG_ERROR, "Invalid audio device index\n");
  521. goto fail;
  522. }
  523. audio_device = [devices objectAtIndex:ctx->audio_device_index];
  524. } else if (ctx->audio_filename &&
  525. strncmp(ctx->audio_filename, "default", 7)) {
  526. NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeAudio];
  527. for (AVCaptureDevice *device in devices) {
  528. if (!strncmp(ctx->audio_filename, [[device localizedName] UTF8String], strlen(ctx->audio_filename))) {
  529. audio_device = device;
  530. break;
  531. }
  532. }
  533. if (!audio_device) {
  534. av_log(ctx, AV_LOG_ERROR, "Audio device not found\n");
  535. goto fail;
  536. }
  537. } else {
  538. audio_device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeAudio];
  539. }
  540. // Video nor Audio capture device not found, looking for AVMediaTypeVideo/Audio
  541. if (!video_device && !audio_device) {
  542. av_log(s, AV_LOG_ERROR, "No AV capture device found\n");
  543. goto fail;
  544. }
  545. if (video_device) {
  546. if (ctx->video_device_index < ctx->num_video_devices) {
  547. av_log(s, AV_LOG_DEBUG, "'%s' opened\n", [[video_device localizedName] UTF8String]);
  548. } else {
  549. av_log(s, AV_LOG_DEBUG, "'%s' opened\n", [[video_device description] UTF8String]);
  550. }
  551. }
  552. if (audio_device) {
  553. av_log(s, AV_LOG_DEBUG, "audio device '%s' opened\n", [[audio_device localizedName] UTF8String]);
  554. }
  555. // Initialize capture session
  556. ctx->capture_session = [[AVCaptureSession alloc] init];
  557. if (video_device && add_video_device(s, video_device)) {
  558. goto fail;
  559. }
  560. if (audio_device && add_audio_device(s, audio_device)) {
  561. }
  562. [ctx->capture_session startRunning];
  563. if (video_device && get_video_config(s)) {
  564. goto fail;
  565. }
  566. // set audio stream
  567. if (audio_device && get_audio_config(s)) {
  568. goto fail;
  569. }
  570. [pool release];
  571. return 0;
  572. fail:
  573. [pool release];
  574. destroy_context(ctx);
  575. return AVERROR(EIO);
  576. }
  577. static int avf_read_packet(AVFormatContext *s, AVPacket *pkt)
  578. {
  579. AVFContext* ctx = (AVFContext*)s->priv_data;
  580. do {
  581. lock_frames(ctx);
  582. CVImageBufferRef image_buffer = CMSampleBufferGetImageBuffer(ctx->current_frame);
  583. if (ctx->current_frame != nil) {
  584. if (av_new_packet(pkt, (int)CVPixelBufferGetDataSize(image_buffer)) < 0) {
  585. return AVERROR(EIO);
  586. }
  587. pkt->pts = pkt->dts = av_rescale_q(av_gettime() - ctx->first_pts,
  588. AV_TIME_BASE_Q,
  589. avf_time_base_q);
  590. pkt->stream_index = ctx->video_stream_index;
  591. pkt->flags |= AV_PKT_FLAG_KEY;
  592. CVPixelBufferLockBaseAddress(image_buffer, 0);
  593. void* data = CVPixelBufferGetBaseAddress(image_buffer);
  594. memcpy(pkt->data, data, pkt->size);
  595. CVPixelBufferUnlockBaseAddress(image_buffer, 0);
  596. CFRelease(ctx->current_frame);
  597. ctx->current_frame = nil;
  598. } else if (ctx->current_audio_frame != nil) {
  599. CMBlockBufferRef block_buffer = CMSampleBufferGetDataBuffer(ctx->current_audio_frame);
  600. int block_buffer_size = CMBlockBufferGetDataLength(block_buffer);
  601. if (!block_buffer || !block_buffer_size) {
  602. return AVERROR(EIO);
  603. }
  604. if (ctx->audio_non_interleaved && block_buffer_size > ctx->audio_buffer_size) {
  605. return AVERROR_BUFFER_TOO_SMALL;
  606. }
  607. if (av_new_packet(pkt, block_buffer_size) < 0) {
  608. return AVERROR(EIO);
  609. }
  610. pkt->pts = pkt->dts = av_rescale_q(av_gettime() - ctx->first_audio_pts,
  611. AV_TIME_BASE_Q,
  612. avf_time_base_q);
  613. pkt->stream_index = ctx->audio_stream_index;
  614. pkt->flags |= AV_PKT_FLAG_KEY;
  615. if (ctx->audio_non_interleaved) {
  616. int sample, c, shift;
  617. OSStatus ret = CMBlockBufferCopyDataBytes(block_buffer, 0, pkt->size, ctx->audio_buffer);
  618. if (ret != kCMBlockBufferNoErr) {
  619. return AVERROR(EIO);
  620. }
  621. int num_samples = pkt->size / (ctx->audio_channels * (ctx->audio_bits_per_sample >> 3));
  622. // transform decoded frame into output format
  623. #define INTERLEAVE_OUTPUT(bps) \
  624. { \
  625. int##bps##_t **src; \
  626. int##bps##_t *dest; \
  627. src = av_malloc(ctx->audio_channels * sizeof(int##bps##_t*)); \
  628. if (!src) return AVERROR(EIO); \
  629. for (c = 0; c < ctx->audio_channels; c++) { \
  630. src[c] = ((int##bps##_t*)ctx->audio_buffer) + c * num_samples; \
  631. } \
  632. dest = (int##bps##_t*)pkt->data; \
  633. shift = bps - ctx->audio_bits_per_sample; \
  634. for (sample = 0; sample < num_samples; sample++) \
  635. for (c = 0; c < ctx->audio_channels; c++) \
  636. *dest++ = src[c][sample] << shift; \
  637. av_freep(&src); \
  638. }
  639. if (ctx->audio_bits_per_sample <= 16) {
  640. INTERLEAVE_OUTPUT(16)
  641. } else {
  642. INTERLEAVE_OUTPUT(32)
  643. }
  644. } else {
  645. OSStatus ret = CMBlockBufferCopyDataBytes(block_buffer, 0, pkt->size, pkt->data);
  646. if (ret != kCMBlockBufferNoErr) {
  647. return AVERROR(EIO);
  648. }
  649. }
  650. CFRelease(ctx->current_audio_frame);
  651. ctx->current_audio_frame = nil;
  652. } else {
  653. pkt->data = NULL;
  654. pthread_cond_wait(&ctx->frame_wait_cond, &ctx->frame_lock);
  655. }
  656. unlock_frames(ctx);
  657. } while (!pkt->data);
  658. return 0;
  659. }
  660. static int avf_close(AVFormatContext *s)
  661. {
  662. AVFContext* ctx = (AVFContext*)s->priv_data;
  663. destroy_context(ctx);
  664. return 0;
  665. }
  666. static const AVOption options[] = {
  667. { "frame_rate", "set frame rate", offsetof(AVFContext, frame_rate), AV_OPT_TYPE_FLOAT, { .dbl = 30.0 }, 0.1, 30.0, AV_OPT_TYPE_VIDEO_RATE, NULL },
  668. { "list_devices", "list available devices", offsetof(AVFContext, list_devices), AV_OPT_TYPE_INT, {.i64=0}, 0, 1, AV_OPT_FLAG_DECODING_PARAM, "list_devices" },
  669. { "true", "", 0, AV_OPT_TYPE_CONST, {.i64=1}, 0, 0, AV_OPT_FLAG_DECODING_PARAM, "list_devices" },
  670. { "false", "", 0, AV_OPT_TYPE_CONST, {.i64=0}, 0, 0, AV_OPT_FLAG_DECODING_PARAM, "list_devices" },
  671. { "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 },
  672. { "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 },
  673. { "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},
  674. { NULL },
  675. };
  676. static const AVClass avf_class = {
  677. .class_name = "AVFoundation input device",
  678. .item_name = av_default_item_name,
  679. .option = options,
  680. .version = LIBAVUTIL_VERSION_INT,
  681. .category = AV_CLASS_CATEGORY_DEVICE_VIDEO_INPUT,
  682. };
  683. AVInputFormat ff_avfoundation_demuxer = {
  684. .name = "avfoundation",
  685. .long_name = NULL_IF_CONFIG_SMALL("AVFoundation input device"),
  686. .priv_data_size = sizeof(AVFContext),
  687. .read_header = avf_read_header,
  688. .read_packet = avf_read_packet,
  689. .read_close = avf_close,
  690. .flags = AVFMT_NOFILE,
  691. .priv_class = &avf_class,
  692. };