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.

877 lines
31KB

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